在数据网格标题模板中传递过滤器文本框

时间:2017-04-03 09:54:48

标签: c# wpf

我有一个Datagrid。我需要在datagrid标题模板中传递过滤器文本框。

我的DataGridFilter.xaml文件包含

<UserControl.....>
 <UserControl.Resources>
        <ResourceDictionary>
 <util:StringToImageConverter x:Key="StringToImageConverter" />
            <util:SelectionModeToStringConverter x:Key="SelectionModeToStringConverter" />

            <DataGridTemplateColumn  x:Key="CustomCheckBoxTemplate">
                <DataGridTemplateColumn.HeaderTemplate>
                    <DataTemplate >
                        <CheckBox Name="ColumnHearderCheckBox" IsThreeState="True" PreviewMouseLeftButtonDown="OnHeaderCheckBoxMouseButtonDown" />
                    </DataTemplate>
                </DataGridTemplateColumn.HeaderTemplate >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox PreviewMouseLeftButtonDown="OnCellCheckBoxPreviewMouseLeftButtonDown" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,
                                      AncestorType=DataGridRow}, Path=IsSelected,Mode=TwoWay}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn >


            <ContextMenu x:Key="ColumnHeaderContextMenu"
                FontSize="{Binding PlacementTarget.FontSize, RelativeSource={RelativeSource Self}}">
                <ContextMenu.ItemContainerStyle>
                    <Style TargetType="{x:Type MenuItem}" >
                        <EventSetter Event= "Click" Handler="OnContextMenuItemClicked" />
                        <Setter Property="IsCheckable" Value="True" />
                        <Setter Property="Header" Value="{Binding Header}" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Visibility}" Value="Visible">
                                <Setter Property="IsChecked" Value="True"/>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Visibility}" Value="Collapsed">
                                <Setter Property="IsChecked" Value="False"/>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Visibility}" Value="Hidden">
                                <Setter Property="IsChecked" Value="False"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ContextMenu.ItemContainerStyle>
            </ContextMenu>
        </ResourceDictionary>
    </UserControl.Resources>
 <Grid Margin="5,0,0,0" Name="grid1" >
   <Grid.Resources>
            <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" >
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="Height" Value="30"/>
                <Setter Property="Foreground" Value="WhiteSmoke"/>
                <Setter Property="FontSize" Value="14"/>
   </Style>
            <DataTemplate x:Key="CustomTemplate">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="{Binding Converter={StaticResource StringToImageConverter}}" Height="30" Width="30" Margin="30,0,0,0" HorizontalAlignment="Right"/>
                </StackPanel>

            </DataTemplate>

            <ContextMenu  x:Key="RowMenu" DataContext="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}">
                <MenuItem Header="Delete" Command="{Binding DeleteCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"  >
                </MenuItem>
                <MenuItem Header="Edit" Command="{Binding EditCommand}"/>
            </ContextMenu>
            <Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource {x:Type DataGridRow}}">
                <Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
            </Style>
        </Grid.Resources>
   <StackPanel Grid.Row="0">

        </StackPanel>
        <DataGrid x:Name="dataGrid"  IsReadOnly="True" ItemsSource="{Binding PatientStudyList}"  SelectionMode="{Binding SelectionMode, Converter={StaticResource SelectionModeToStringConverter}}"
                  AlternationCount="2" GridLinesVisibility="Horizontal" AutoGenerateColumns="False"  BorderThickness="1" 
                  RowStyle="{StaticResource DefaultRowStyle}" HorizontalAlignment="Stretch"  >

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Unloaded">
                    <i:InvokeCommandAction Command="{Binding DataGridUnloadedCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
  <DataGrid.ColumnHeaderStyle>
                <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
                    <Setter Property="ContextMenu" Value="{StaticResource ColumnHeaderContextMenu}" />
                    <Setter Property="Height" Value="60" />
                </Style>
            </DataGrid.ColumnHeaderStyle>
        </DataGrid>
    </Grid>
</UserControl>

和DatagridFilter.Xamal.cs包含在下面的代码中。

  public partial class DatagridFilter: UserControl
    {
        public delegate void SearchTextChanged(Dictionary<string, string> filter);
        public event SearchTextChanged SearchTextChangedEvent;
        private RepositoryBrowserCtrlViewModel _viewModel;
        private readonly ContextMenu _columnHeaderContextMenu = null;
        private object SearchValue { get; set; }
        public GenericTextBoxFilter _genericfilter;
        private readonly IEventAggregator _iEventAggregator;
       // private Dictionary<string, string> filterValues = new Dictionary<string, string>();
        /// <summary>
        /// Constructor
        /// </summary>
        public RepositoryBrowserCtrl()
        {
            InitializeComponent();
            //_columnHeaderContextMenu = TryFindResource("ColumnHeaderContextMenu") as ContextMenu;
            dataGrid.SelectionChanged += OnDataGridSelectionChanged;
            DataContextChanged += OnDataContextChanged;
        }
        /// <summary>
        /// Handler for DataGridSelection changed event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null == _viewModel)
            {
                return;
            }
            if (dataGrid.SelectionMode == DataGridSelectionMode.Extended)
            {
                _viewModel.HandleSelectionChange(e.RemovedItems, e.AddedItems);

                CheckBox columnHeaderCheckBox = VisualTreeHelpers.FindChild<CheckBox>(dataGrid, "ColumnHearderCheckBox");
                int dataSourceCount = dataGrid.ItemsSource.Cast<Object>().Count();
                if (dataSourceCount != 0 && dataGrid.SelectedItems.Count == dataSourceCount)
                    columnHeaderCheckBox.IsChecked = true;
                else if (dataGrid.SelectedItems.Count > 0)
                    columnHeaderCheckBox.IsChecked = null;
                else
                    columnHeaderCheckBox.IsChecked = false;
            }
            else
            {
                IList addItems = new ArrayList(1);
                addItems.Add(dataGrid.SelectedItem);
                _viewModel.HandleSelectionChange(null, addItems);


            }
            e.Handled = true;

        }

        /// <summary>
        /// Handler for DataContextChnaged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            _viewModel = e.NewValue as RepositoryBrowserCtrlViewModel;
            if (null == _viewModel)
            {
                return;
            }
            // Update Column
            CreateColumns();


            dataGrid.ItemsSource = _viewModel.PatientStudyList;
        }  

        /// <summary>
        /// Create DataGridColumn from RepositoryBrowserColumn
        /// </summary>
        private void CreateColumns()
        {
            //Add Default check box template.
            List<RepositoryBrowserColumn> columList = _viewModel.ColumSettings;
            DataGridColumn column1 = TryFindResource("CustomCheckBoxTemplate") as DataGridColumn;
            column1.CanUserReorder = false;
            column1.CanUserResize = false;
            column1.DisplayIndex = 0;
            dataGrid.Columns.Add(column1);

            dataGrid.FrozenColumnCount++;

            foreach (RepositoryBrowserColumn col in columList)
            {
                DataGridBoundColumn column = null;


                //Check for column type
                if (col.Type == "Icon")
                {
                    column = new CustomBoundColumn();
                    column.Header = col.Header;
                    column.Visibility = Visibility.Visible;
                    if (col.IsHidden)
                    {
                        column.Visibility = Visibility.Collapsed;
                    }
                    column.Binding = new Binding(col.Binding);
                    column.CanUserReorder = col.CanUserReOrder;
                    column.CanUserResize = col.CanUserResize;
                    column.CanUserSort = col.CanUserSort;
                    column.Width = col.Width;
                    column.MinWidth = col.MinWidth;
                  ((CustomBoundColumn)column).TemplateName = "CustomTemplate";
                }
                else
                {
                    column = new DataGridTextColumn();
column.Header = col.Header;

                    if (col.IsHidden)
                    {
                        column.Visibility = Visibility.Collapsed;
                    }
                    Binding binding = new Binding(col.Binding);
                    column.Binding = binding;
                    column.CanUserReorder = col.CanUserReOrder;
                    column.CanUserResize = col.CanUserResize;
                    column.CanUserSort = col.CanUserSort;
                    column.Width = col.Width;
                    column.MinWidth = column.MinWidth;
 }
                dataGrid.Columns.Add(column);
                if (_columnHeaderContextMenu != null)
                {
                    Binding columnBinding = new Binding();
                    MenuItem menuItem = new MenuItem();
                    columnBinding.Source = column;
                    menuItem.SetBinding(DataContextProperty, columnBinding);
                    _columnHeaderContextMenu.Items.Add(menuItem);
                }
            }


        }
        private string GetColumnName(string name)
        {
            string columnName = string.Empty;
            switch (name)
            {
                case "Name":
                    {
                        columnName = "PatientName";
                        break;
                    }
                case "ID":
                    {
                        columnName = "PatientId";
                        break;
                    }
                case "ExamName":
                    {
                        columnName = "ExamName";
                        break;
                    }
                default:
                    {
                        columnName = name;
                        break;
                    }
            }
            return columnName;
        }


        /// <summary>
        /// When context menu clicked reset the column visibility 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnContextMenuItemClicked(object sender, RoutedEventArgs e)
        {
            MenuItem columnHeaderMenuItem = sender as MenuItem;
            if (columnHeaderMenuItem != null)
            {
                DataGridColumn col = columnHeaderMenuItem.DataContext as DataGridColumn;
                if (columnHeaderMenuItem.IsChecked)
                {
                    col.Visibility = Visibility.Visible;
                }
                else
                {
                    col.Visibility = Visibility.Collapsed;
                }
            }
        }

        /// <summary>
        /// Event handler for a check box click on the header
        /// It should allowed to check if selection mode is Single.
        /// Check all datagrid rows based on the selection 
        /// </summary>
        /// <param name="sender">Check box</param>
        /// <param name="e"> event arguments </param>
        void OnHeaderCheckBoxMouseButtonDown(object sender, RoutedEventArgs e)
        {
            CheckBox headerCheckBox = sender as CheckBox;
            if (dataGrid.SelectionMode == DataGridSelectionMode.Single)
            {
                return;
            }
            var newValue = headerCheckBox != null && !headerCheckBox.IsChecked.GetValueOrDefault();
            if (headerCheckBox != null) headerCheckBox.IsChecked = newValue;

            if (newValue)
                dataGrid.SelectAll();
            else
                dataGrid.UnselectAll();

            e.Handled = true;

        }

        /// <summary>
        /// Handle Check box click on the cell .
        /// When Check box clicks , Select/Unselect Datagrid Row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCellCheckBoxPreviewMouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            var chk = (CheckBox)sender;
            var row = VisualTreeHelpers.FindAncestor<DataGridRow>(chk);
            var newValue = !chk.IsChecked.GetValueOrDefault();

            row.IsSelected = newValue;
            chk.IsChecked = newValue;
            e.Handled = true;
        }
   }
}

我需要根据下图显示结果: enter image description here

怎么做。?

0 个答案:

没有答案