执行以下操作是否有简单的技巧?
<Binding RelativeSource="{RelativeSource AncestorType=UserControl OR Window}" Path="Tag" />
我只是想绑定到顶级父级的 Tag 属性,它可以是 UserControl 或 Window。但是请注意,从当前控件到父控件的距离是任意的,所以我不能使用AncestorLevel
.
好吧,如果它是你想要的黑客:)
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>
您可以只使用MultiBinding
而不是Binding
为此,然后做一个简单IMultiValueConverter
的查找“值”中不为空的第一项(或DependencyProperty.UnsetValue
,在使用可视化树时往往会弹出。
这是一种不那么老套的方法,对我来说非常有效。