我在表格上有一些标签。有些工作,有些不工作。不同之处在于那些不起作用的设置为多重绑定(bind),但在这个特定实例中它们似乎无法正确绑定(bind)。
这是两个标签的示例,一个有效,一个无效。它们都与父级共享相同的网格,并且我绑定(bind)到的对象设置为页面的 DataContext,因此它们也应该共享上下文。
Context 对象本质上采用以下形式(为隐私/安全而抽象)
class Model {
public SubModel Parent {get;set;}
}
class SubModel {
public string PropA {get;set;}
public string PropB {get;set;}
public string PropC {get;set;}
}
作品:
<Label Content="{Binding Parent.PropA}"/>
不起作用:
<Label>
<Label.Content>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="Parent.PropB"/>
<Binding Path="Parent.PropC"/>
</MultiBinding>
</Label.Content>
</Label>
我知道这种语法有效,因为我有一些其他的 MultiBindings 采用相同的形式并有效,不同之处在于它们的页面直接绑定(bind)到“Parent”,并且它们的绑定(bind)看起来更像
<Binding Path="PropB"/>
问题似乎出在使用标记并尝试引用绑定(bind)上下文的子属性的子属性时。为什么会发生这种情况,我该如何解决?
我也试过将 Label 本身的 DataContext 绑定(bind)到 Parent 对象,这也不起作用。
为什么会发生这种情况,我如何在不在容器上创建一堆不同的 DataContext 并以这种方式进行处理的情况下解决这个问题?
最佳答案
绑定(bind)的 StringFormat
属性仅在绑定(bind)的源属性为 string
类型时应用。
Label 的 Content
属性属于 object
类型,因此未应用 StringFormat
,并且绑定(bind)系统提示缺少多绑定(bind)转换器。
当您使用 TextBlock 而不是 Label 时,目标属性将是字符串类型的 Text
。因此,StringFormat 将被应用:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="Parent.PropB"/>
<Binding Path="Parent.PropC"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
即使使用单个绑定(bind),也可以执行以下操作:
<TextBlock Text="{Binding Parent.PropA, StringFormat=Content: {0}}"/>
但这不会:
<Label Content="{Binding Parent.PropA, StringFormat=Content: {0}}"/>
但是,Label 有一个 ContentStringFormat
属性:
<Label Content="{Binding Parent.PropA}" ContentStringFormat="Content: {0}"/>
关于c# - WPF MultiBinding 到 Model.ChildProperty 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246093/