我在从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
为假时检查,并且在检查时为真。
是什么导致这种情况?
答案 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
但不是两个。