C#和XAML之间的双向数据绑定更新

时间:2014-07-13 14:18:20

标签: c# wpf

我正在尝试了解WPF中的数据绑定。我有一个测试应用程序(如下)。我试图让数据更新进出XAML。即....

  1. 当我在XAML TextBox中编辑值时,我想要在中的c#对象 代码隐藏更新。
  2. 如果c#发生变化(按下按钮模拟),我想要更新XAML TextBox。
  3. 我希望XAML列表框中的项目能够针对上述任一更改进行更新。
  4. 到目前为止,我已经获得No.1工作,但无法弄清楚如何让其他2人工作。

    ... MainWindow.xaml

    <Window x:Class="MySimpleProgram.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="725"
            >
        <StackPanel Name="StackPanel1" Orientation="Horizontal">
    
            <TextBox Name="TextBox2" Text="{Binding Path=FirstName, Mode=TwoWay}" Height="23"/>
    
            <Button Name="Button1" Content="Change C# obj people[0]" Width="175" Height="20" Click="Button1_Click" />
    
            <ListBox Name="listPeople" DisplayMemberPath="FirstName"/>
    
        </StackPanel>
    </Window>
    

    ... MainWindow.xaml.cs

    namespace MySimpleProgram
    {
    
        public class Person
        {
            public string FirstName { get; set; }
            public int Age { get; set; }
        }
    
    
        public partial class MainWindow : Window
        {
            public ObservableCollection<Person> people;
    
            public MainWindow()
            {
                InitializeComponent();
    
                people = new ObservableCollection<Person>(){ 
                    new Person{ FirstName = "Shirley", Age = 22}, 
                    new Person{ FirstName = "Roy", Age = 29},  
                    new Person{ FirstName = "Manuel", Age = 34} };
    
                StackPanel1.DataContext = people[0];
    
                listPeople.ItemsSource = people;
            }
    
    
            private void Button1_Click(object sender, RoutedEventArgs e)
            {
                people[0].FirstName += "y";
            }
    
        }
    }
    

    4)另外如果我按下button1,listBox会更新textBox而不是+="y"部分提供的值 - 导致这种情况发生的原因是什么?

2 个答案:

答案 0 :(得分:1)

作为Sajeetharan said,您需要实施INotifyPropertyChanged,但要查看您的other question您实施的“不正确”。它不是“错误的”,因为它仍然可以工作,但它不是几乎所有人都使用的模式,如果你使用它们,可能会让其他开发者更难。

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;    

    private String _firstName;
    private String _age;

    public string FirstName
    {
        get { return _firstName; }
        set
        {
            //If the value did not change we shouldn't trigger the event.
            if(Object.Equals(_firstName, value))
                return;

            _firstName = value;

            //Use a reuseable function to "raise" your event so it makes 
            // multiple properties easier. The standard name for this raising
            // function is OnXxxxxxx where Xxxxxxx is your Event name and should
            // be private or protected.
            OnPropertyChanged("FirstName")
        }
    }

    private OnPropertyChanged(string propertyName)
    {
        //Storing the event in a local temporary variable prevents
        // a potential NullRefrenceException when you are working
        // in a multitreaded enviorment where the last subscriber
        // could unsubscribe between the null check and the invocation.
        var tmp = PropertyChanged;
        if (tmp != null)
            tmp(this, new PropertyChangedEventArgs(propertyName));
    }

    public int Age 
    { 
        get {return _age;} 
        set
        {
            if(Object.Equals(_age, value))
                return;

            _age= value;
            OnPropertyChanged("Age")
        }
    }
}

答案 1 :(得分:0)

如果您希望在应用程序中进行双向绑定,那么您的数据对象Person必须实现INotifyPropertyChanged