如何绑定CheckBox到Window的Topmost依赖属性?
问题解答
你的错误出在RelativeSource的使用方式上——你把它赋值给了Source属性,但正确的做法是直接使用Binding的RelativeSource属性来配置相对查找规则。
错误原因
你之前的代码里,Binding的Source属性接收了一个RelativeSource对象,这会让Binding误以为这个RelativeSource实例就是要绑定的数据源,所以它会去这个RelativeSource对象上找Topmost属性,自然找不到,才抛出了那个错误。
正确写法
把RelativeSource从Source属性里拿出来,作为Binding的RelativeSource参数:
<CheckBox IsChecked="{Binding Path=Topmost, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">Topmost</CheckBox>
也可以用简化写法(省略Path=和Mode=,因为FindAncestor是RelativeSource的默认模式之一):
<CheckBox IsChecked="{Binding Topmost, RelativeSource={RelativeSource AncestorType=Window}}">Topmost</CheckBox>
这样Binding就会正确向上查找最近的Window类型祖先,然后绑定它的Topmost依赖属性,不需要给窗口设置x:Name。
内容的提问来源于stack exchange,提问作者Niko O
相关产品推荐
相关产品推荐

