简体   繁体   中英

Two way Data Binding update between C# and XAML

I'm trying to learn about Data Binding in WPF. I have a test app (below). I am trying to get data updates to work both into and out of XAML. Ie...

  1. When I edit the value in the XAML TextBox I want the c# object in the
    code-behind to update.
  2. And if the c# changes (simulated by pressing the button), I want the XAML TextBox to update.
  3. I want the items in the XAML list box to update for either of the above changes.

So far I have got No.1 to work, but cant figure out how to get the other 2 to work.

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) Also if I press button1, the listBox updates with the value that has been supplied by the textBox and not the +="y" part - what is causing this to happen?

As Sajeetharan said you need to implment INotifyPropertyChanged , however looking at your other question you implemented it "not correctly". It is not "wrong" as it will still work but it is not the pattern almost everyone else uses and will likely make it harder on other developers if you work with them.

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")
        }
    }
}

如果要在应用程序中进行双向绑定,则数据对象Person必须实现INotifyPropertyChanged

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM