如果我做错了或者我有什么东西丢失了,但是当我使用编译时绑定时INotifyPropertyChanged工作并且当我使用传统绑定时它不起作用时,我不会这样做。
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中
<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
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";
}
}
我真的很困惑,因为当你使用编译时绑定绑定时,它工作正常。发生了什么事?
答案 0 :(得分:3)
我没有看到您将当前DataContext设置到对象的任何位置。
public MainPage()
{
this.InitializeComponent();
st = new Students();
this.DataContext = st;
}
OR :您在XAML中设置了一个datacontext,但是您没有引用它。
<Page.DataContext>
<local:Students/>
</Page.DataContext>
如果您打算使用它,则需要从代码中引用该对象。
private void change_name(object sender, RoutedEventArgs e)
{
((Students)this.DataContext).Name = "MM";
}
答案 1 :(得分:0)
我的情况与作者非常相似(如果不一样),我做的唯一一件事就是修改它是我的视图模型是一个公共属性。如果是上述示例,则会Students st;
更改为public Students st {get; set;}