问题
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
<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";
}
}
I am really confused, because when you bind with compile time binding, it works fine. What's going on?
回答1:
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: 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";
}
回答2:
I had a situation very similar to the author (if not the same) and only thing I did to fix it is I made my view model a public property. In case of the example above, it would be Students st;
changed to public Students st {get; set;}
来源:https://stackoverflow.com/questions/33376304/inotifypropertychanged-not-working-with-traditonal-binding-but-works-with-compil