【发布时间】:2011-08-05 09:37:38
【问题描述】:
我在更新 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; }
}
现在 somehting 正在工作,因为当我运行应用程序时,我看到“测试值绑定”正确显示在我的视图中,问题是当我的 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 中,我正在更改处理饼图的片段代码中的数据上下文。我通过更改绑定 epression 来解决此问题,以便绑定元素成为 Snapshot.xaml 的父级,在我的情况下为 StackPanel 'sp'({Binding ElementName=sp,Path=DataContext.Session.Test})。除了这个愚蠢的错误之外,我的原始代码中真正缺少的是 INotifyPropertyChanged 实现,TwoWay 绑定是不必要的。
谢谢
路易斯
【问题讨论】:
-
这是一个结构良好的问题,但是您是否真的将
INotifyPropertyChanged添加到class Session声明行? -
是的,Session 实现了 INotifyPropertyChanged。
标签: silverlight dependency-properties