在DataGrid使用中,当有很多列时,可能会遇到选择性的显示列,那么该怎么办呢,我是这么做的:
首先让MenuItem绑定DataGrid的所有列,然后将MenuItem的Item模板列改为CheckBox,在让CheckBox的Content绑定MenuItem的Header,让IsChecked绑定列是否显示隐藏(这里有一个Convert转换器),代码如下:
Xaml:
<MenuItem Header="显示隐藏列" ItemsSource="{Binding PlacementTarget.Columns, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ContextMenu}, Mode=FindAncestor}}">
<MenuItem.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header,UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding Visibility,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource DataGridColumnVisibilityConvert}}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
其中DataGridColumnVisibilityConvert转换器在Resource中引用,然后有一个类实现:
<UserControl.Resources>
<local:DaraGridColumnVisibility x:Key="DataGridColumnVisibilityConvert"/>
</UserControl.Resources>
CS:
public class DaraGridColumnVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool flag = false;
Visibility vis = (Visibility)value;
switch (vis)
{
case Visibility.Hidden:
flag = false;
break;
case Visibility.Visible:
flag = true;
break;
default:
break;
}
return flag;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool flag = System.Convert.ToBoolean(value);
if (flag)
{
return Visibility.Visible;
}
else
{
return Visibility.Hidden;
}
}
}
OK,这样就可以进行自由选择显示列的,是不是很简单!