Qwe*_*tie 35 wpf binding nested properties
我可以绑定到属性,但不能绑定到另一个属性中的属性.为什么不?例如
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"...>
...
<!--Doesn't work-->
<TextBox Text="{Binding Path=ParentProperty.ChildProperty,Mode=TwoWay}"
Width="30"/>
Run Code Online (Sandbox Code Playgroud)
(注意:我不是要做master-details或者其他任何东西.这两个属性都是标准的CLR属性.)
更新:问题是我的ParentProperty依赖于XAML中的一个对象被初始化.不幸的是,该对象后来在XAML文件中定义而不是Binding,因此当Binding读取ParentProperty时,该对象为null.由于重新排列XAML文件会搞砸布局,我能想到的唯一解决方案是在代码隐藏中定义Binding:
<TextBox x:Name="txt" Width="30"/>
// after calling InitializeComponent()
txt.SetBinding(TextBox.TextProperty, "ParentProperty.ChildProperty");
Run Code Online (Sandbox Code Playgroud)
小智 44
您也可以设定DataContext为TextBox在XAML(我不知道这是否是最佳的解决方案,但至少你不必手动代码隐藏做任何事情,除了实现的INotifyPropertyChanged).当你TextBox已经DataContext(继承DataContext)你编写这样的代码:
<TextBox
DataContext="{Binding Path=ParentProperty}"
Text="{Binding Path=ChildProperty, Mode=TwoWay}"
Width="30"/>
Run Code Online (Sandbox Code Playgroud)
请注意,直到你的DataContextfor TextBox不准备绑定Text属性将不会'建立' - 你可以添加FallbackValue='error'为Binding参数 - 它将像指示器一样,将显示绑定是否正常.
Ken*_*art 24
我能想到的是,在创建ParentProperty之后Binding它会被更改,并且它不支持更改通知.链中的每个财产都必须支持变更通知,无论是通过成为DependencyProperty还是通过实施INotifyPropertyChanged.