我似乎在更新绑定属性时,无法让我的WPF UI更新。以下是我的视图模型类定义:
namespace WpfModel
{
class AppModel : INotifyPropertyChanged
{
private int _count = 7;
public int Count { get { return _count; }
set { _count = value; OnPropertyChanged("Count"); } }
public void Increment()
{
Count++;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs("prop");
handler(this, e);
}
}
};
}
这是我的简单UI在以下XAML中绑定的:
<Window x:Class="WpfModel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfModel"
Title="WPF Data Model Demo" Height="128" Width="284" >
<Window.DataContext>
<vm:AppModel />
</Window.DataContext>
<Grid Height="Auto" Width="Auto">
<Button Margin="0,0,12,12" Name="IncButton" Height="23" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75" Click="IncButton_Click" Content="Increment" />
<Label Content="Count Variable:" Height="28" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" />
<Label Height="28" Margin="116,12,0,0" Name="CountLabel" VerticalAlignment="Top" HorizontalAlignment="Left" Width="40" Content="{Binding Path=Count}" />
</Grid>
</Window>
应用程序的定义如下:
namespace WpfModel
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private AppModel _model = new AppModel();
public MainWindow()
{
InitializeComponent();
//_model = new AppModel();
}
private void IncButton_Click(object sender, RoutedEventArgs e)
{
}
}
}
当应用程序启动时,一切都很顺利,甚至标签最初显示模型的Count属性中的任何值。调用increment可以正确更新模型,并且直接增加代码中所示的Count属性也可以正常工作。
问题在于,PropertyChanged事件处理程序似乎从未被添加。我可以通过调试器逐步执行代码并查看属性中的值更新,我甚至可以看到对OnPropertyChanged的调用,但PropertyChanged处理程序本身始终为空。
我的绑定有问题吗?
我正在使用MSVC 2010 Express。