gpt4 book ai didi

c# - INotifyPropertyChanged 不适用于传统绑定(bind),但适用于编译绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:32 24 4
gpt4 key购买 nike

如果我做错了什么或者我遗漏了什么,我不会这样做,但是当我使用编译时绑定(bind)时 INotifyPropertyChanged 起作用,而当我使用传统绑定(bind)时它不起作用。

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";
}


}

主页.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";
}
}

我真的很困惑,因为当你使用编译时绑定(bind)进行绑定(bind)时,它工作正常。怎么回事?

最佳答案

我没有看到您将当前 DataContext 设置为您的对象的任何地方。

 public MainPage()
{
this.InitializeComponent();
st = new Students();
this.DataContext = st;
}

:您正在 XAML 中设置数据上下文,但未引用它。

<Page.DataContext>
<local:Students/>
</Page.DataContext>

如果您打算使用它,则需要从代码中引用该对象。

 private void change_name(object sender, RoutedEventArgs e)
{
((Students)this.DataContext).Name = "MM";
}

关于c# - INotifyPropertyChanged 不适用于传统绑定(bind),但适用于编译绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33376304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com