WPF应用程序的意外行为
本文关键字:意外 应用程序 WPF | 更新日期: 2023-09-27 18:09:55
我正在学习WPF,我编写了一个使用"绑定"概念的小示例。但是程序的行为与我所期望的不同。
我有Person类,它有两个属性:FirstName和LastName。这个类实现了INotifyPropertyChanged接口,因此我可以使用它进行绑定。
class Person : INotifyPropertyChanged
{
private string firstName;
private string lastName;
public string FirstName
{
get { return firstName; }
set { NotifyPropertyChanged("FirstName"); firstName = value; }
}
public string LastName
{
get { return lastName; }
set { NotifyPropertyChanged("LastName"); lastName = value; }
}
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
public event PropertyChangedEventHandler PropertyChanged;
}
然后我有一些XAML代码。
<Window x:Class="BughouseClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Name="stackPanel">
<TextBox Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
<TextBox Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Button Click="Fill">
Click
</Button>
</StackPanel>
</Grid>
MainClass code:
public partial class MainWindow : Window
{
Person person;
public MainWindow()
{
InitializeComponent();
person = new Person();
person.FirstName = "Bruce";
person.LastName = "Lee";
stackPanel.DataContext = person;
}
void Fill(object sender, RoutedEventArgs e)
{
person.FirstName = "John";
person.LastName = "Jones";
}
}
我期待,当我点击点击按钮,FirstName和LastName属性将改变,我将看到他们立即在文本框中。但是我必须点击两次才能看到文本框中的变化。请问,有人知道为什么吗?
. .我发现,当我改变MainClass代码为:
public partial class MainWindow : Window
{
Person person;
int i = 1;
public MainWindow()
{
InitializeComponent();
person = new Person();
person.FirstName = "Bruce";
person.LastName = "Lee";
stackPanel.DataContext = person;
}
void Fill(object sender, RoutedEventArgs e)
{
if (i == 1)
{
person.FirstName = "John";
person.LastName = "Jones";
i++;
}
if (i == 2)
{
person.FirstName = "Jim";
person.LastName = "Parker";
}
}
}
它"神奇地"起作用了!我可以立即在文本框中看到约翰·琼斯。但我无法解释为什么。任何帮助都会非常感激。
通知需要在您更新了后台字段后发生。
:
set { NotifyPropertyChanged("FirstName"); firstName = value; }
应:set { firstName = value; NotifyPropertyChanged("FirstName"); }
当你调用NotifyPropertyChanged时,绑定触发器就会发生,因此,如果你先拥有它,那么当绑定被触发时,你的字段不会得到更新,你最终会有旧的值仍然显示。
一个好的做法是先检查是否相等,以避免触发NotifyPropertyChanged
set
{
if (firstName == value) return;
firstName = value;
NotifyPropertyChanged("FirstName");
}