WPF,XAML数据网格 - 仅在最后一行启用的上下文菜单

时间:2015-11-04 09:16:07

标签: wpf xaml datagrid contextmenu

我必须创建一个上下文菜单,但它应该只在最后一行启用。在所有其他行中,应禁用它。我有1行或x行。

<DataGrid.ContextMenu>
    <ContextMenu>
        <MenuItem Name="change_entry" Header="change entry"/>
    </ContextMenu>
</DataGrid.ContextMenu>

1 个答案:

答案 0 :(得分:1)

您可以使用ContextMenu.IsEnabledDataGrid.SelectedIndex属性绑定到DataGrid.Items.CountIMultiValueConverter属性。如果更改了任何值,它将更新。这是XAML:

    <Window x:Class="DataGridMenuTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataGridMenuTest"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <local:SelectedRowToBoolConverter x:Key="SelectedRowToBoolConverter"/>
    </Window.Resources>

    <Grid>
        <DataGrid Name="MainGrid">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <ContextMenu.IsEnabled>
                                <MultiBinding  Mode="OneWay" Converter="{StaticResource SelectedRowToBoolConverter}">
                                    <Binding ElementName="MainGrid" Path="SelectedIndex"/>
                                    <Binding ElementName="MainGrid" Path="Items.Count"/>
                                </MultiBinding>
                            </ContextMenu.IsEnabled>

                            <MenuItem Name="change_entry" Header="change entry"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGrid.RowStyle>           
    </DataGrid>
    </Grid>
</Window>

这里是转换器代码:

public class SelectedRowToBoolConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue)
            return false;

            int selectedIndex = (int)values[0];
            int rowsCount = (int)values[1];

            return (selectedIndex == rowsCount - 1);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }