简体   繁体   English

如何在WPF C#中以编程方式隐藏DataGrid的单元格?

[英]How to programmatically hide cells of a DataGrid in wpf c#?

Would there be any way to hide/collapse specific dataGrid cells in code-behind? 有什么方法可以在代码隐藏中隐藏/折叠特定的dataGrid单元格吗? Since my datatable columns are created at run-time, I'm unable to specify properties (in XAML) to properly setup these datatriggers, templateselectors, etc. I am, however, able to locate the exact cells I want to collapse by looping through the datatable to add the row/column indexes to a List (below). 由于我的数据表列是在运行时创建的,因此我无法指定属性(在XAML中)以正确设置这些数据触发器,模板选择器等。但是,我能够通过循环查找要折叠的确切单元格数据表以将行/列索引添加到列表(如下)。

I know this is unorthodox, but I've been reading threads for weeks trying to solve this and nothing has gotten me there. 我知道这是非正统的,但是我已经读了数周的线程来尝试解决这个问题,但是没有任何东西可以帮助我。 This seems like would be the simplest solution (if possible). 这似乎是最简单的解决方案(如果可能)。

private static List<KeyValuePair<int, int>> GetCellsToHide(DataTable pivotTable)
{
    var noCellValueList = new List<KeyValuePair<int, int>>();
    foreach (DataRow row in pivotTable.Rows)
    {
        foreach (DataColumn col in pivotTable.Columns)
        {
            if (row[col].ToString() == "HideMe")
            {
                int rowIndex = pivotTable.Rows.IndexOf(row);
                int colIndex = pivotTable.Columns.IndexOf(col);

                noCellValueList.Add(new KeyValuePair<int, int>(rowIndex, colIndex));

            }
        }
    }

    return noCellValueList;
}

Edit: datatemplate & converter information 编辑:数据模板和转换器信息

I'm currently building the datagrid by autogeneratingcolumns. 我目前正在通过自动生成列来构建数据网格。 I know the names of all other columns so I can narrow down to the dynamically generated ones. 我知道所有其他列的名称,因此可以缩小到动态生成的列。 My dynamic columns are DataTemplate5, for instance (simplified version below): 我的动态列是DataTemplate5,例如(下面是简化版):

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.Column.Header.ToString() == "Name")
        e.Column.Header = "File Name";

    else
    {
        string origHeader = e.Column.Header.ToString();

        DataGridTemplateColumn templateColumn = new DataGridTemplateColumn    //create new template column
        {
             Header = origHeader,
             CellTemplate = (DataTemplate)Resources["DataTemplate5"]

        }; 

        e.Column = templateColumn; // Replace the auto-generated column with the templateColumn.    
    }
}

But since I don't have the property (column) names to bind to, I haven't been able to bind it correctly. 但是由于我没有要绑定的属性(列)名称,因此我无法正确绑定它。 Here's my latest attempt at hiding cells via the datatemplate & ivalueconverter: 这是我通过datatemplate和ivalueconverter隐藏单元格的最新尝试:

<DataTemplate x:Key="DataTemplate5">
    <DataTemplate.Resources>
        <local:StringToVisibilityConvertor x:Key="VisibilityConvertor" />
    </DataTemplate.Resources>
    <StackPanel Visibility="{Binding BindsDirectlyToSource=True, Converter={StaticResource VisibilityConvertor}}">
        <Button Name="Button1" Click="ButtonClick">
            <Button.Style>
                <Style  TargetType="Button">
                    <Style.Setters>
                        <Setter Property="Background" Value="Orange"/>
                    </Style.Setters>
                </Style>
            </Button.Style>
        </Button>
    </StackPanel>
</DataTemplate>

And the converter: 和转换器:

public class StringToVisibilityConvertor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.ToString() != "HideMe")
            return Visibility.Visible;
        return Visibility.Collapsed;
    }

Because of the dynamic columns, I was not able to get my bindings to work. 由于存在动态列,因此无法使绑定生效。 In the end, I stumbled upon a great article by Paul Stovell on how to create the grid using the column index as the binding path. 最后,我偶然发现了Paul Stovell撰写的一篇很棒的文章,内容涉及如何使用列索引作为绑定路径来创建网格。 After doing this, I created a datatemplate for all columns and hid the cell with datatrigger: 完成此操作后,我为所有列创建了一个数据模板,并使用datatrigger隐藏了该单元格:

http://paulstovell.com/blog/dynamic-datagrid http://paulstovell.com/blog/dynamic-datagrid

Must admit, I've never gone this far in tweaking the auto-generation of columns - I rarely use auto-generated columns, although I guess you have to as you don't know the columns until run time. 必须承认,在调整列的自动生成方面,我从未走过这么远-我很少使用自动生成的列,尽管我猜您必须这样做,因为您直到运行时才知道这些列。

If it were me, I'd tweak the template thus: 如果是我,我将这样调整模板:

<DataTemplate x:Key="DataTemplate5">
    <Button Name="Button1" Click="ButtonClick" Background="Orange" Content="{Binding ???}" >
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding ???}" Value="HideMe">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

Saves the need for the converter. 节省了转换器的需求。 Question now though is what to put for the ???. 现在的问题是,该放置什么? Try nothing - ie just {Binding}. 不要尝试-即{Binding}。

You may also need to add a little to your code behind: 您可能还需要在代码后面添加一些内容:

                 DataGridTemplateColumn templateColumn = new DataGridTemplateColumn    //create new template column
                 {
                     Header = origHeader,
                     CellTemplate = (DataTemplate)Resources["DataTemplate5"],
                     SortMemberPath = e.Column.SortMemberPath
                 };  

Actually, try that first - it may be enough, along with some debugging in your value converter. 实际上,首先尝试一下-可能就足够了,并在值转换器中进行一些调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM