WPF绑定到自定义DependencyProperty - IsChecked有时与属性值相反

时间:2017-04-27 08:05:31

标签: c# wpf xaml user-controls

我在从UserControl派生的WPF中有一个控件。该控件具有名为IsDraggable的Dependency属性。它是这样实现的:

public static readonly DependencyProperty IsDraggableProperty =
    DependencyProperty.Register(nameof(IsDraggable), typeof(bool), typeof(MyUserControl));
public bool IsDraggable
{
    get { return (bool)this.GetValue(IsDraggableProperty); }
    set { this.SetValue(IsDraggableProperty, value); }
}

private void IsDraggableMenuItemClick(object sender, RoutedEventArgs e)
    => this.IsDraggable = !this.IsDraggable;

在XAML中,UserControl有一个ContextMenu:

<UserControl.ContextMenu>
    <ContextMenu>
        <!-- other menu items here -->
        <MenuItem
            Header="Draggable"
            IsCheckable="True"
            Click="IsDraggableMenuItemClick"
            IsChecked="{Binding Path=MyUserControlsNameProperty, ElementName=IsDraggable}" />
    </ContextMenu>
</UserControl.ContextMenu>

使用此UserControl,我在主窗口中添加了一个,在外部UserControl中添加了一个。在外部控件中,可检查MenuItem的工作方式与预期相同,但在内部控件中,IsDraggable为假时检查,并且在检查时为真。

是什么导致这种情况?

1 个答案:

答案 0 :(得分:0)

为什么要在事件处理程序中显式设置IsDraggable属性?您应该将IsChecked的{​​{1}}属性绑定到MenuItem属性:

UserControl

处理<UserControl.ContextMenu> <ContextMenu> <!-- other menu items here --> <MenuItem Header="Draggable" IsCheckable="True" IsChecked="{Binding Path=PlacementTarget.IsDraggable, RelativeSource={RelativeSource AncestorType=ContextMenu}}" /> </ContextMenu> </UserControl.ContextMenu> 的{​​{1}}和Checked eventw:

Unchecked
MenuItem

但不是两个。