我正在尝试了解WPF中的数据绑定。我有一个测试应用程序(如下)。我试图让数据更新进出XAML。即....
到目前为止,我已经获得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"
部分提供的值 - 导致这种情况发生的原因是什么?
答案 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