执行以下操作有没有简单的方法?指定多个RelativeSource.AncestorTypes
<Binding RelativeSource="{RelativeSource AncestorType=UserControl OR Window}" Path="Tag" />
我只想绑定到顶级父级的Tag属性,它可以是UserControl或Window。但请注意,从当前控件到父项的距离是任意的,所以我不能使用AncestorLevel
。
执行以下操作有没有简单的方法?指定多个RelativeSource.AncestorTypes
<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>
嗯,这是一个有趣的方法!目前我通过使用MainWindowViewModel和我需要的东西来解决这个问题。我在xaml中使用FindAncestor Window绑定,或者使用IoC将MainWindowViewModel传递给孩子,并访问我需要的方式。 – failedprogramming 2013-03-10 22:22:55
@菲尔:完美。想知道为什么在这个世界上我没有想出这个简单的想法。 – dotNET 2013-03-11 03:20:04
一个黑客可以只使用MultiBinding
代替Binding
这个,然后做一个简单的IMultiValueConverter
是发现在“值”的第一个项目,是不是空(或DependencyProperty.UnsetValue
,与Visual树工作时往往会弹出。
这是要做到这一点少哈克的方式,和完美的作品对我来说。
没有理由列出的标签在你的问题标题。请参阅http:/ /meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles讨论为什么不需要。 – Patrick 2013-03-10 17:19:42
另外,类似stukselbax回应你的[其他问题](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles)写你可能可以解决这个问题带有标记扩展,或者带有一些值转换器。你尝试过吗? – Patrick 2013-03-10 17:21:06
@帕特里克:感谢代码使用建议。这很有道理。至于stukselbax的回答(您可能想要更正您评论中的链接),这一点对我而言非常复杂。正如你在Phil的回答中看到的那样,解决方案要简单得多。 – dotNET 2013-03-11 03:26:54