码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-09-07 21:35:23      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:dynamic   方法   class   panel   sys   .sh   owb   stat   binding   

直接上代码,首先是一个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的问题

标签:dynamic   方法   class   panel   sys   .sh   owb   stat   binding   

原文地址:http://www.cnblogs.com/lionwang/p/7491685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!