问题描述
如果我做错了什么或者我缺少什么,我不会,但是当我使用编译时绑定进行操作时INotifyPropertyChanged可以工作,而使用传统绑定进行操作时则无法工作。
I don't if I am doing something wrong or if there is something I am missing but the INotifyPropertyChanged works when I do it with compile time binding and doesn't work when I do it with traditional binding.
public class Students : INotifyPropertyChanged
{
private string name;
private string surname;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Name
{
get { return name; }
set
{
if(value != name)
{
name = value;
NotifyPropertyChanged();
}
}
}
public string Surname
{
get { return surname; }
set
{
if (value != surname)
{
surname = value;
NotifyPropertyChanged();
}
}
}
public Students()
{
Name = "John";
Surname = "Smith";
}
}
MainPage.xaml
MainPage.xaml
<Page.DataContext>
<local:Students/>
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Margin="0,200,0,0">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Surname}"/>
<Button Content="Change Name" Click="change_name"/>
<Button Content="Change Surname" Click="change_surname"/>
</StackPanel>
</Grid>
MianPage.xaml.cs
MianPage.xaml.cs
public sealed partial class MainPage : Page
{
Students st;
public MainPage()
{
this.InitializeComponent();
st = new Students();
}
private void change_name(object sender, RoutedEventArgs e)
{
st.Name = "MM";
}
private void change_surname(object sender, RoutedEventArgs e)
{
st.Surname = "SS";
}
}
我真的很困惑,因为当您绑定编译时时间绑定,效果很好。
I am really confused, because when you bind with compile time binding, it works fine. What's going on?
推荐答案
我看不到要在其中将当前DataContext设置为对象的任何地方。
I don't see any place in which you are setting the current DataContext to your object.
public MainPage()
{
this.InitializeComponent();
st = new Students();
this.DataContext = st;
}
OR :您正在设置数据上下文XAML,但您没有引用它。
OR: You are setting a datacontext in your XAML, but you aren't referencing it.
<Page.DataContext>
<local:Students/>
</Page.DataContext>
如果要使用该对象,则需要从代码中引用该对象。
You would need to reference that object from code if you intend to use it.
private void change_name(object sender, RoutedEventArgs e)
{
((Students)this.DataContext).Name = "MM";
}
这篇关于INotifyPropertyChanged不适用于传统绑定,但适用于编译绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!