首页 > 解决方案 > 绑定到 Window 祖先的元素

问题描述

在这段代码中,我在标签中正确打印了窗口标题

<Window x:Class="Crono4.Views.MainWindow"
...>
    <DockPanel>
        <Grid ...>
            <RadioButton x:Name="buttonProduct" Content="Product"/>  
            <RadioButton .../>
        </Grid>
        <Grid>
            <Label x:Name="label" Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Title}"/>
        </Grid>
    </DockPanel>
</Window>

但是如果我想引用按钮的名称,这是行不通的:

<Label x:Name="label" Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=buttonProduct.Content}"/>

为什么?谢谢,

标签: wpfbinding

解决方案


因为buttonProduct不是窗口的属性并且只能绑定到公共属性。

您可以尝试使用 anElementName绑定到RadioButton

<Label x:Name="label" Content="{Binding ElementName=buttonProduct, Path=Content}"/>

推荐阅读