我将ContextMenu标记绑定到所有者标记时遇到问题。我这样想:
<Style x:Key="DefaultTextBox" TargetType="{x:Type TextBox}">
<Setter Property="BorderBrush" Value="{DynamicResource ThemeSecondary}"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource Mode=Self}}"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu x:Name="uiContexMenu">
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Command="Cut" Header="Cut">
<MenuItem.Icon>
<Viewbox Width="16" Height="16">
<TextBlock FontFamily="{DynamicResource IconFont}" Text=""/>
</Viewbox>
</MenuItem.Icon>
</MenuItem>
<MenuItem Command="Copy" Header="Copy">
<MenuItem.Icon>
<Viewbox Width="16" Height="16">
<TextBlock FontFamily="{DynamicResource IconFont}" Text=""/>
</Viewbox>
</MenuItem.Icon>
</MenuItem>
<MenuItem Command="Paste" Header="Paste">
<MenuItem.Icon>
<Viewbox Width="16" Height="16">
<TextBlock FontFamily="{DynamicResource IconFont}" Text=""/>
</Viewbox>
</MenuItem.Icon>
</MenuItem>
<CollectionContainer Collection="{Binding ElementName=uiContexMenu, Path=Tag(local:Extensions.ExtendCommands)}"/>
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
</Setter.Value>
</Setter>
如果用Snoop(xaml debuger)绑定显示错误:
System.Windows.Data.Error:4:无法找到绑定源 参考'RealativeSource FindAncestor, AncestorType ='System.Windows.Controls.TextBox',AncestorLevel ='1''。 BindingExpression:Path = Tag;的DataItem = NULL;目标元素是 '文本菜单'(名称= 'uiContextMenu'); target属性是'Tag'(类型 '对象')
有人可以帮忙吗?谢谢
答案 0 :(得分:0)
我希望这是因为ItemControl
ContextMenu
试图访问尚未指定的TemplatedParent
属性。
无论如何,这将解决您的问题。
<Application.Resources>
<Style TargetType="MenuItem">
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</Application.Resources>
参考: How to get rid of annoying HorizontalContentAlignment binding warning?
希望有所帮助。