如何为WPF网格的整行添加上下文菜单?

时间:2018-03-02 13:53:27

标签: .net wpf xaml

我在WPF网格中有一些控件(不是数据网格)。我想为整个网格行添加一个上下文菜单。我已经尝试将上下文菜单添加到RowDefinition但这似乎不起作用。我还尝试在整行上添加边框或矩形,背景设置为透明,以及上下文菜单。这可行,但后来我无法与其背后的控件进行交互。

这是我的示例XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Content="Some Property" />
    <TextBox Grid.Row="0" Grid.Column="1" Text="Actual" />
    <TextBox Grid.Row="0" Grid.Column="2" Text="Setpoint" />
    <Button Grid.Row="0" Grid.Column="3" Content="Set" />
    <Label Grid.Row="1" Grid.Column="0" Content="Another Property" />
    <TextBox Grid.Row="1" Grid.Column="1" Text="Actual" />
    <TextBox Grid.Row="1" Grid.Column="2" Text="Setpoint" />
    <Button Grid.Row="1" Grid.Column="3" Content="Set" />
</Grid>

1 个答案:

答案 0 :(得分:2)

您可以将上下文菜单设为静态:

<Grid>
    <Grid.Resources>
       <ContextMenu x:Key="MyContext">
          <MenuItem Header="Test"/>
          <MenuItem Header="Test 1"/>
          <MenuItem Header="Test 2"/>
       </ContextMenu>
    </Grid.Resources>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    //Extra border added
    <Border Grid.Column="0" Grid.ColumnSpan="4" Background="Transparent" ContextMenu="{StaticResource MyContext}"/>

    // ContextMenu="{StaticResource MyContext}" added
    <Label Grid.Row="0" Grid.Column="0" Content="Some Property" ContextMenu="{StaticResource MyContext}"/>

    // ContextMenu="{StaticResource MyContext}" added
    <TextBox Grid.Row="0" Grid.Column="1" Text="Actual" ContextMenu="{StaticResource MyContext}"/>

    // ContextMenu="{StaticResource MyContext}" added
    <TextBox Grid.Row="0" Grid.Column="2" Text="Setpoint" ContextMenu="{StaticResource MyContext}"/>

    // ContextMenu="{StaticResource MyContext}" added
    <Button Grid.Row="0" Grid.Column="3" Content="Set" ContextMenu="{StaticResource MyContext}"/>
    <Label Grid.Row="1" Grid.Column="0" Content="Another Property" />
    <TextBox Grid.Row="1" Grid.Column="1" Text="Actual" />
    <TextBox Grid.Row="1" Grid.Column="2" Text="Setpoint" />
    <Button Grid.Row="1" Grid.Column="3" Content="Set" />
</Grid>

我还添加了一个额外的边框来覆盖行的其余部分。