1. 實現DataGrid column的顯示和隱藏功能; (1). 定義ContextMenu ,該ContextMenu僅可使用於DataGrid的DataGridColumnHeader; (2). 自定義顯示隱藏的制轉換器; 2. 在實現DataGridColumn Filter 功能時,可 ...
1. 實現DataGrid column的顯示和隱藏功能;
(1). 定義ContextMenu ,該ContextMenu僅可使用於DataGrid的DataGridColumnHeader;
<ContextMenu x:Key="StudyDataGridHeaderContextMenu" ItemsSource="{Binding Columns, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type DataGrid}, Mode=FindAncestor}}"> <ContextMenu.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding Header,UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding Path=Visibility,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,Converter={StaticResource DataGridColumnVisibilityConvert}}"/> </DataTemplate> </ContextMenu.ItemTemplate> </ContextMenu>
(2). 自定義顯示隱藏的制轉換器;
public class DataGridColumnVisibility : 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; } } }
2. 在實現DataGridColumn Filter 功能時,可以採用在DataGrid的外部(列頭上)綁定對應的TextBox控制項,並設置其樣式與DataGridColumn基本一致,綁定寬度的方式來實現;
(1). 綁定TextBox;
<TextBox x:Name="txt2" Style="{StaticResource textBoxStyle}" Grid.Column="1" VerticalAlignment="Top" Foreground="Indigo" TabIndex="0" BorderThickness="1" Text="{Binding Data_idFilter_text, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Visibility="{Binding Visibility,ElementName=studyID}"> <TextBox.Width> <MultiBinding Converter="{StaticResource VisibilityToWidthConverter}"> <Binding Path="Visibility" ElementName="studyID"></Binding> <Binding Path="ActualWidth" ElementName="studyID"></Binding> </MultiBinding> </TextBox.Width> <i:Interaction.Triggers> <i:EventTrigger EventName="TextChanged"> <i:InvokeCommandAction Command="{Binding LoadDataCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBox>
(2). 自定義多值轉換器;
class VisibilityToWidthConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { Visibility vis = (Visibility)values[0]; double result = double.MinValue; switch(vis) { case Visibility.Hidden: result = 0; break; case Visibility.Visible: result = (double)values[1]; break; default: result = 0; break; } return result; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }