【发布时间】:2021-12-06 03:15:22
【问题描述】:
这是我的 XAML 代码:
<Label x:Name="currentPage" Width="45" Height="25" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="{Binding CurrentPageNo, Mode=OneWay}" />
这是我的代码隐藏:
private int currentPageNo;
public int CurrentPageNo
{
get { return currentPageNo; }
set { currentPageNo = value; NotifyPropertyChanged("CurrentPageNo"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void gotoPrevious(object sender, RoutedEventArgs e)
{ this.currentPageNo--;}
private void gotoPrevious(object sender, RoutedEventArgs e)
{ this.currentPageNo++;}
当我按下下一页按钮或上一页按钮时,currentPageNo 会发生变化,但这不会反映在 UI 中。
当我这样做时它会起作用。
private int currentPageNo;
public int CurrentPageNo
{
get { return currentPageNo; }
set { currentPageNo = value; NotifyPropertyChanged("currentPageNo"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void gotoPrevious(object sender, RoutedEventArgs e)
{
this.currentPageNo--;
NotifyPropertyChanged("currentPageNo");
}
private void gotoPrevious(object sender, RoutedEventArgs e)
{
this.currentPageNo++;
NotifyPropertyChanged("currentPageNo");
}
无论我在哪里更改值,我都必须从所有地方通知。这感觉不对。我错过了什么吗?还是打算用第二种方式完成?
【问题讨论】:
-
改用
this.CurrentPageNo,目前您只是在编辑字段,而不是属性,即NotifyPropertyChanged不会被调用。 -
@imsmn 如果我必须使用 CurrentPageNo (public int) 在代码隐藏中进行操作,那么 currentPageNo (private int) 有什么用?
public int CurrentPageNo { get { return currentPageNo; } set { currentPageNo = value; NotifyPropertyChanged("CurrentPageNo"); } }这东西不是连接“currentPageNo”和“CurrentPageNo”吗?还是你想说我必须使用“this.currentPageNo++”而不是“currentPageNo++”? -
WPF 绑定仅适用于 properties(这就是 public int 的名称)。 This 只是一个关键字。
NotifyPropertyChanged仅在您的属性的设置器中调用,您肯定在调试时注意到了这一点。这就是它目前不起作用的原因:你没有打电话给你的财产。 -
在开始 WPF 之前,您应该了解您的语言。至少知道基础知识。否则你不会走得很远。 C# 比 WPF 更容易学习。如果你想成功,你肯定必须改变学习方式。 C# 有属性和字段。现在您正在引用一个字段 - 属性的支持字段。为了执行该属性的 set() 和 get(),您必须引用该属性。我强烈建议从Properties 开始学习基础知识。
-
currentPageNo 字段只有一个功能 - 存储属性的值。除了其属性的主体外,您不应该在任何地方引用该字段。我建议您以某种方式在名称中标记此类字段。为此,我将其命名为 Low Line(
_),并将其仅应用于存储属性值的字段。因此,我大大降低了意外错误的可能性。
标签: wpf xaml data-binding properties inotifypropertychanged