单击“事件”以右键单击“事件数据绑定模板”

本文关键字:单击 事件 右键 数据绑定 | 更新日期: 2023-09-27 18:35:32

我正在使用WPF MVVM

我做了以下DataTemplate

<DataTemplate DataType="{x:Type r:CustomControl}">
        <Border x:Name="bord" BorderThickness="0" Width="150" Height="150" Margin="0"
                BorderBrush="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Background}" 
                Background="{Binding RelativeSource={RelativeSource AncestorType={x:Type con:Control}, Mode=FindAncestor}, Path=TileColorPair[0]}"
                ContextMenu="{StaticResource CMenu}">
            <Button Width="{Binding Size}" Height="{Binding Size}">
                <Button.Template>
                    <ControlTemplate>
                        <Grid >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Image x:Name="img"  Grid.Row="0" Source="{Binding ImageUrl}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            <Label Grid.Row="1" Content="{Binding Text}" FontFamily="{DynamicResource DefaultFont}" FontSize="{DynamicResource {x:Static SystemFonts.CaptionFontSizeKey}}"
                                   Foreground="White"  VerticalAlignment="Bottom" HorizontalAlignment="Center"/>
                        </Grid>
                    </ControlTemplate>
                </Button.Template>
            </Button>
        </Border>

我在Border上关联了一个ContextMenu.每个菜单都有一个特定的Command

    <ContextMenu x:Key="CMenu">
        <MenuItem Command="{Binding UpdateCommand}" Header="Update">
            <MenuItem.Icon>
                <Image Width="45" Height="45" Source="/Assembly;component/Resources/edit.png"/>
            </MenuItem.Icon>
        </MenuItem>
        <MenuItem Command="{Binding SelectCommand}" Header="Select">
            <MenuItem.Icon>
                <Image Width="45" Height="45"  Source="/Assembly;component/Resources/search.png" />
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
如何将激活ContextMenu的右键单击

事件绑定到左键单击?

单击“事件”以右键单击“事件数据绑定模板”

Border 元素上创建一个新的左按钮处理程序:

<Border x:Name="Win"
        Width="40"
        Height="40"
        Background="Purple"
        MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp">

然后添加以下内容:

private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    var mouseDownEvent =
        new MouseButtonEventArgs(Mouse.PrimaryDevice,
            Environment.TickCount,
            MouseButton.Right)
        {
            RoutedEvent = Mouse.MouseUpEvent,
            Source = Win,
        };

    InputManager.Current.ProcessInput(mouseDownEvent);
}

它的作用,基本上是将左键单击映射到右键单击。