我有自定义画布(DesignerCanvas),用户可以为此画布添加一些控件。在添加任何控件画布之前,首先将其包装为自定义控件(Designer Item),然后将该控件添加到画布。
这是在此代码项目文章中完成的 -
WPF图设计师 - http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx
我为DesignerCanvas和DesignerItem添加了一个上下文菜单,其菜单项名为“Lock”。我还在画布中添加了一个名为“IsLocked”的属性来锁定画布。
现在,在上下文菜单中,如果画布被锁定,我想显示一个复选标记,为此,我将IsLocked属性绑定到MenuItem的“IsChecked”属性。问题是它适用于DesignerCanvas cantext菜单,但不适用于DesignerItems上下文菜单。
DesignerCanvas ContextMenu代码,这很好用 -
<!-- Context menu for DesignerCanvas -->
<ContextMenu x:Key="DesignerCanvasContextMenu">
<!-- Other menu items -->
<MenuItem IsCheckable="True" Header="Lock"
IsChecked="{Binding Path=IsLocked, Mode=TwoWay,
RelativeSource={RelativeSource AncestorType={x:Type locl:DesignerCanvas}}}"
Command="{x:Static local:DesignerCanvas.LockUnLock}"
CommandParameter="{Binding RelativeSource={RelativeSource Self},
Path=IsChecked}"
CommandTarget="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}">
</MenuItem>
</ContextMenu>
还需要为DesignerItem菜单执行相同的操作。我试过这样做,但它不起作用 -
<!-- Context menu for DesignerItem -->
<ContextMenu x:Key="DesignerItemContextMenu">
<!-- Other menu items -->
<MenuItem IsCheckable="True" Header="Lock"
IsChecked="{Binding Path=Parent.IsLocked, Mode=TwoWay,
RelativeSource={RelativeSource AncestorType={x:Type locl:DesignerItem}}}"
Command="{x:Static local:DesignerCanvas.LockUnLock}"
CommandParameter="{Binding RelativeSource={RelativeSource Self},
Path=IsChecked}"
CommandTarget="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}">
</MenuItem>
</ContextMenu>
我也尝试使用PlacementTarget执行此操作但未成功。由于DesignerItem是DesignerCanvas的孩子,因此不应该无法获得DesignerCanvas以及它的属性。我做错了什么,有什么想法吗?
更新
我正在使用DesignerCanvas和Designer Item附加上下文菜单,如下所示 -
<!-- DesignerItem || Style -->
<Style TargetType="{x:Type locl:DesignerItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DesignerItem}">
<Grid x:Name="PART_Grid" Cursor="SizeAll"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}
,Path=.}"
ContextMenu="{StaticResource DesignerItemContextMenu}">
<!-- other template parts -->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- DesignerCanvas || Style -->
<Style
TargetType="{x:Type locl:DesignerCanvas}">
<Setter
Property="ContextMenu"
Value="{StaticResource DesignerCanvasContextMenu}" />
</Style>
答案 0 :(得分:1)
只是一个快速猜测:
您是否尝试过在DesignerItem上设置Contextmenu的方式与Canvas相同?像这样:
<Style TargetType="{x:Type locl:DesignerItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DesignerItem}">
<Grid x:Name="PART_Grid" Cursor="SizeAll"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}
,Path=.}">
<!-- other template parts -->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter
Property="ContextMenu"
Value="{StaticResource DesignerItemContextMenu}" />
</Style>
除此之外,我真的建议您在应用程序上启动Snoop并在上下文菜单中查找绑定错误