我对你有坏消息。
里面DependencyObject.SetValue
检查位于,检查是否新值等于旧值。因此,如果您绑定到A.B
,并且更改A.B.C
会产生PropertyChanged事件A.B
,Binding
mechanizm将处理此事件,甚至会呼叫DependencyObject.SetValue
。但之后(由于旧的和新的A.B
值相等)没有更改将应用于DP。
为了实现正确的DP启动,您应该创建一个新的A.B实例,最终令人头痛。
修订
你可以使用可冻结对象,它支持通知,当它的属性改变它已经改变了。 DependencyObject正确地与Freezables一起工作,所以下一个例子就是你所需要的。
模型类:
public class A
{
public A()
{
this.B = new B();
}
public B B
{
get; private set;
}
}
public class B : Freezable, INotifyPropertyChanged
{
protected override Freezable CreateInstanceCore()
{
return new B();
}
private string _c = "initial string";
public string C
{
get
{
return _c;
}
set
{
this._c = value;
this.OnPropertyChanged("C");
this.OnChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
var safe = this.PropertyChanged;
if (safe != null)
{
safe(this, new PropertyChangedEventArgs(name));
}
}
}
的XAML:
<StackPanel>
<TextBox Text="{Binding A.B.C}" />
<TextBox Text="{Binding MyProperty.C}" />
<Button Click="Button_Click"/>
</StackPanel>
后面的代码:
public partial class TextBoxesView : UserControl
{
public TextBoxesView()
{
InitializeComponent();
this.A = new A();
this.DataContext = this;
BindingOperations.SetBinding(this, TextBoxesView.MyPropertyProperty, new Binding("A.B"));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.A.B.C = DateTime.Now.ToString();
}
public A A
{
get;
private set;
}
public B MyProperty
{
get
{
return (B)this.GetValue(TextBoxesView.MyPropertyProperty);
}
set
{
this.SetValue(TextBoxesView.MyPropertyProperty, value);
}
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty",
typeof(B),
typeof(TextBoxesView),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, (d, e) => { }));
}
您可能需要一个'模式= TwoWay'添加到绑定。但是,我不确定我是否正确理解了你的问题,你可以添加一些代码吗? – Damascus 2011-04-05 12:53:20
如果您稍微创建类结构并在此处粘贴它的代码,看起来好多了... – 2011-04-05 12:53:24