绑定到窗口的依赖属性

问题描述 投票:0回答:1

我想创建一个复选框来切换窗口的 Topmost 属性。

如果 TopMost 是 ViewModel 的属性,我会使用这个:

<CheckBox IsChecked="{Binding Path=Topmost}">Topmost</CheckBox>

但是

Topmost
Window
上的 DependencyProperty,其中
CheckBox
位于其中。
我尝试了以下方法:

<CheckBox IsChecked="{Binding Path=Topmost, Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">Topmost</CheckBox>

但我在运行时收到以下错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'Topmost' property not found on 'object' ''RelativeSource' (HashCode=12083439)'. BindingExpression:Path=Topmost; DataItem='RelativeSource' (HashCode=12083439); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1')

我的错误是什么?

我可以给窗口一个

x:Name="MyWindow"
,然后使用

<CheckBox IsChecked="{Binding Path=Topmost, ElementName=MyWindow}">Topmost</CheckBox>

相反,但如果可能的话我宁愿避免

x:Name

wpf data-binding
1个回答
1
投票

您必须设置 Binding 的

RelativeSource
属性而不是
Source
属性:

<CheckBox Content="Topmost"
          IsChecked="{Binding Topmost,
                      RelativeSource={RelativeSource AncestorType=Window}}"/>
    
© www.soinside.com 2019 - 2024. All rights reserved.