定义并与CollectionView绑定后,是否可以在WPF DataGrid中隐藏列? [英] Is it possible to hide columns in WPF DataGrid when defined and bound with CollectionView?

查看:66
本文介绍了定义并与CollectionView绑定后,是否可以在WPF DataGrid中隐藏列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试此处的示例

http://msdn.microsoft.com/en-us/library/ff407126

我想向该用户添加控件可以定义哪些列可见。能容易做到吗?

I would like to add a control that user can define which columns are visible. Can this be done easily?

我发现 http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the -datacontext-is-not-herited / ,但这是不同的,因为它不使用CollectionView和CollectionViewSource。

I found http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ but it's different since it's not using CollectionView and CollectionViewSource.

感谢& BR -Matti

Thanks & BR -Matti

推荐答案

可以用很多方法完成。一种方法是编辑DataGrid列标题的样式。列标题样式的示例可以在以下位置找到:

It can be done many ways. One way is to edit the Style for DataGrid's column headers. An example of a style for column headers can be found in :

更改WPF DataGrid列标题样式,菜单隐藏在代码隐藏中吗?

而不是像上面的文章那样在ControlTemplate中有菜单,可以有一个像这样的列标题按钮:

Instead of having menu in ControlTemplate like in article above there can be a button like here for the column header:

<Button Grid.Column="2" Name="MultiButton" MouseRightButtonDown="MultiButton_MouseRightButtonDown" Click="MultiButton_Click" Visibility="Hidden">X</Button>

按钮使用第二个鼠标按钮打开popupmenu,然后单击以删除该列。默认情况下,该按钮是隐藏的,因此当鼠标移至列标题时必须触发该按钮:

Button opens popupmenu with 2nd mouse button and click is supposed to remove the column. The button is hidden by default so there has to be trigger to make button visible when mouse moves to column header:

<Trigger Property="IsMouseOver" Value="True" >
    <Setter Property="Visibility" TargetName="DeleteColumn" Value="Visible" />                            
</Trigger>

因为所有列都有按钮,单击事件必须整理出要隐藏的列:

Because all the columns have the button the click event have to sort out which column to hide:

private void MultiButton_Click(object sender, RoutedEventArgs e)
{
   object dataContext = ((FrameworkElement)sender).DataContext;
   foreach (DataGridColumn col in dataGrid1.Columns)
   {
       if (col.Header.ToString() == dataContext.ToString())
       {
           col.Visibility = Visibility.Hidden;
       }
   }
}

这可能不是最好的做到这一点的方法,但确实可行。

This might not be the best way to do it, but it works.

这篇关于定义并与CollectionView绑定后,是否可以在WPF DataGrid中隐藏列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆