[WPF]解决模板中ContextMenu绑定CommandParameter的问题

Posted 逍遥岚轩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[WPF]解决模板中ContextMenu绑定CommandParameter的问题相关的知识,希望对你有一定的参考价值。

直接上代码,首先是一个ContextMenu的模板:

<ContextMenu x:Key="Menu" BorderThickness="0.3" FontSize="13" DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
        <MenuItem Header="复制" Command="{Binding Source={x:Static vm:ViewModelLocator.Instance},Path=MainWindowVM.CopyImageCommand}"
                  CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}" CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" />
        <MenuItem Header="另存为..." Command="{Binding Source={x:Static vm:ViewModelLocator.Instance},Path=MainWindowVM.SaveImageCommand}"
                  CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}" CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" />
    </ContextMenu>

然后是DataTemplate的内容:

<DataTemplate x:Key="CustomerImageDataTemplate">
            <Button Command="{Binding DataContext.ShowImageCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Cursor="Hand"
                    CommandParameter="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=StackPanel}}" Padding="3">
                <Button.Template>
                    <ControlTemplate TargetType="Button">
                        <Grid>
                            <Border  Name="imgBorder"  BorderBrush="{StaticResource ListBorder}" CornerRadius="3" BorderThickness="0"
                                Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" Margin="0">
                            </Border>
                            <Image x:Name="ImageMsg" Source="{Binding TextContent}" Stretch="Uniform" Width="120" Height="80"
                                   ContextMenu="{StaticResource Menu}" Tag="{Binding}">
                                <Image.OpacityMask>
                                    <VisualBrush Visual="{Binding ElementName=imgBorder, Mode=OneTime}" />
                                </Image.OpacityMask>
                            </Image>
                        </Grid>
                    </ControlTemplate>
                </Button.Template>
            </Button>
    </DataTemplate>

上面的Button还展示了将图片四角设置为圆角的方法。

以上是关于[WPF]解决模板中ContextMenu绑定CommandParameter的问题的主要内容,如果未能解决你的问题,请参考以下文章

WPF ContextMenu 在MVVM模式中绑定 Command及使用CommandParameter传参

WPF:将 ContextMenu 绑定到 MVVM 命令

WPF:将 ListBox ContextMenu 的命令参数绑定到 ListBox 的选定项

WPF ContextMenu:MenuItem 图标可见性绑定错误

WPF中ContextMenu怎么控制显示与不显示

WPF 控件模板不根据依赖属性绑定值更改