我必须创建一个上下文菜单,但它应该只在最后一行启用。在所有其他行中,应禁用它。我有1行或x行。
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Name="change_entry" Header="change entry"/>
</ContextMenu>
</DataGrid.ContextMenu>
答案 0 :(得分:1)
您可以使用ContextMenu.IsEnabled
将DataGrid.SelectedIndex
属性绑定到DataGrid.Items.Count
和IMultiValueConverter
属性。如果更改了任何值,它将更新。这是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();
}
}