【发布时间】:2015-05-16 02:15:36
【问题描述】:
作为练习,我决定在 WPF 中创建一个自行车齿轮计算器。我使用触发OnPropertyChanged() 的setter 创建了两个私有字段,但我有一个数据绑定属性ratio,它表现为“只读”,因为它是动态计算的。当我运行程序时,文本框显示,初始值正确显示,属性更改处理程序中的“工作”字被显示,但ratio TextBlock 没有更新。
我怀疑这是由于“获取”属性的方式,我想知道是否绝对有必要为每个添加一个私有字段,我想知道这是否应该有任何 DependencyProperty ......但实际上我已达到我对此的知识极限,无法让这个琐碎的程序运行。
这是我的模型:
class SingleGearsetModel : INotifyPropertyChanged
{
public SingleGearsetModel()
{
crank = 44;
cog = 16;
}
private int _crank;
private int _cog;
public int crank {
get{return _crank;}
set{
_crank = value;
OnPropertyChanged("crank");
}
}
public int cog {
get{return _cog;}
set{
_cog = value;
OnPropertyChanged("cog");
}
}
public double ratio
{
get {
return (double)crank / (double)cog;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string arg)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(arg));
Console.Writeline("working");
}
}
} // end class
这是我的 XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CalculadorFixaWPF.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<DockPanel x:Name="LayoutRoot">
<TextBox Text="{Binding crank, Mode=TwoWay}"/>
<TextBox Text="{Binding cog, Mode=TwoWay}"/>
<TextBlock Text="{Binding ratio, StringFormat={}{0:0.00}}"/>
</DockPanel>
</Window>
这是在我的代码隐藏 (MainWindow.xaml.cs) 中:
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
this.DataContext = new SingleGearsetModel();
}
}
感谢阅读!
【问题讨论】:
标签: wpf data-binding notifications