我必須創建一個上下文菜單,但它只應在最後一行啓用。在所有其他行中,它應該被禁用。我有1或x行。WPF,XAML Datagrid - 僅在最後一行啓用上下文菜單
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Name="change_entry" Header="change entry"/>
</ContextMenu>
</DataGrid.ContextMenu>
我必須創建一個上下文菜單,但它只應在最後一行啓用。在所有其他行中,它應該被禁用。我有1或x行。WPF,XAML Datagrid - 僅在最後一行啓用上下文菜單
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Name="change_entry" Header="change entry"/>
</ContextMenu>
</DataGrid.ContextMenu>
你可以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();
}
}
你如何填充您的數據網格?我認爲解決方案將取決於它。一些更多的代碼將有助於。 – Jose