1. 程式人生 > >WPF資料繫結---雙向繫結

WPF資料繫結---雙向繫結

定義繫結型別時,實現/引用INotifyPropertyChanged介面

public class StudentData:INotifyPropertyChanged
{
    private int id;
    private string name;
    
    public int Id
    {
        get { return id; }
        set
        {
            id = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Id"));
        }
    }

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("Name"));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

XAML:

<Grid>
    <StackPanel Name="stackPanel" Orientation="Vertical" VerticalAlignment="Center" Width="60">
        <TextBox Name="IdData" Text="{Binding Id}"/>
        <TextBox Name="NameData" Text="{Binding Name}"/>
        <Button Name="btn" Content="changId" Click="bnt_Click"/>
        <Button Name="btn2" Content="確定" Click="btn2_Click"/>
    </StackPanel>
</Grid>

XAML.cs

public MainWindow()
    {
        InitializeComponent();
        Init();
    }

    private StudentData stu;
    private void Init()
    {
        stu = new StudentData();
        stu.Id = 1000;
        stu.Name = "Judy";

        stackPanel.DataContext = stu;
    }

    private void bnt_Click(object sender, RoutedEventArgs e)
    {
        stu.Id++;
        stackPanel.DataContext = stu;
    }

    private void btn2_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Id:"+ stu.Id + "\nName:"+stu.Name);
    }
}