Cor*_*One 5 wpf inotifypropertychanged
我知道我在这里做错了什么.请看一看并指出我的错误.
我会在文本框中看到"Peter"但按钮点击后没有"Jack".
我的课
namespace App
{
class Person : INotifyPropertyChanged
{
private string name;
public String Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
public Person()
{
Name = "Peter";
}
public void SetName(string newname)
{
Name = newname;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
我的XAML
<Window x:Class="test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
Title="MainWindow" Height="400" Width="400">
<Grid>
<Grid.Resources>
<app:Person x:Key="person"/>
</Grid.Resources>
<TextBox Width="100" Height="26" Text="{Binding Source={StaticResource person}, Path=Name, Mode=TwoWay}" />
<Button Content="Button" Height="23" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
Run Code Online (Sandbox Code Playgroud)
而我的代码隐藏
public partial class MainWindow : Window
{
Person person;
public MainWindow()
{
InitializeComponent();
person = new Person();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
person.SetName("Jack");
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
你有两个Person实例.PropertyChanged在静态资源中不为null
这不是StaticResources的真正含义.摆脱静态资源,将绑定更改为:
{Binding Path=Name, Mode=TwoWay}
Run Code Online (Sandbox Code Playgroud)
并将其添加到您的构造函数:
DataContext = person;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13592 次 |
| 最近记录: |