我在更新UserControl/View的一个依赖属性时遇到了一些问题。
我有一个主视图(MainView.xaml),其中声明了一系列其他用户控件。其中一个如下所示:
<local:Snapshot BrandID="{Binding Path=Session.Test}" />
我的 Snapshot.xaml 文件中有一个 TextBlock:
<TextBlock Text="Sample text" x:Name="brandIDTBlock" />
我的Snapshot.xaml.cs文件有以下依赖属性:
public string BrandID
{
get { return (string)GetValue(BrandIdProperty); }
set { SetValue(BrandIdProperty, value); }
}
public static readonly DependencyProperty BrandIdProperty = DependencyProperty.Register("BrandID", typeof(string), typeof(Snapshot), new PropertyMetadata(new PropertyChangedCallback(OnBrandIdChange)));
private static void OnBrandIdChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (Snapshot)d;
control.brandIDTBlock.Text = (string)e.NewValue;
}
Session是MainView的一个属性,当Session对象中的Test属性发生变化时,我希望我的brandIDTBlock TextBlock得到更新。
Test属性声明如下:
private string _test = "Test Value Binding";
public string Test
{
get { return _test; }
set { _test = value; }
}
现在某些东西正在工作,当我运行应用程序时,我可以看到“测试值绑定”在我的视图中正确显示,问题是当Test的值在我的Session对象中更改时,更改不会传播到视图。
我还尝试实现INotifyPropertyChanged接口,方法如下:
public string Test
{
get { return _test; }
set
{
_test = value;
OnPropertyChanged("Test");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
但它仍然没有更新。
更新:事实证明这是一个新手错误。在我的Snapshot.xaml.cs中,我正在更改处理饼图的代码块中的数据上下文。我通过更改绑定表达式,使绑定元素成为Snapshot.xaml的父级(在我的情况下为StackPanel 'sp' ({Binding ElementName=sp, Path=DataContext.Session.Test}))来解决了这个问题。除了这个愚蠢的错误之外,我原始代码中真正缺少的是INotifyPropertyChanged实现,双向绑定是不必要的。
谢谢
Luis
INotifyPropertyChanged
添加到了class Session
声明行中? - AnthonyWJones