1

执行以下操作是否有简单的技巧?

<Binding RelativeSource="{RelativeSource AncestorType=UserControl OR Window}" Path="Tag" />

我只是想绑定到顶级父级的 Tag 属性,它可以是 UserControl 或 Window。但是请注意,从当前控件到父控件的距离是任意的,所以我不能使用AncestorLevel.

4

2 回答 2

3

好吧,如果它是你想要的黑客:)

public partial class MainWindow : ITopLevel
{
    public MainWindow()
    {
        InitializeComponent();

        Tag = "I'm at the top";
    }
}

public interface ITopLevel
{
    // optionally specify Tag in the interface, it will work either way
    object Tag { get; set; }
}

<Grid>
    <Button Content="{Binding Path=Tag, RelativeSource={RelativeSource 
            FindAncestor, AncestorType={x:Type Demo:ITopLevel}}}"/>
</Grid>
于 2013-03-10T20:43:41.587 回答
0

您可以只使用MultiBinding而不是Binding为此,然后做一个简单IMultiValueConverter的查找“值”中不为空的第一项(或DependencyProperty.UnsetValue,在使用可视化树时往往会弹出。

这是一种不那么老套的方法,对我来说非常有效。

于 2014-04-30T08:36:57.580 回答