【问题标题】:WPF Datagrid Template column edit event and alternating column colorWPF Datagrid 模板列编辑事件和交替列颜色
【发布时间】:2011-04-21 23:55:57
【问题描述】:

我一直在使用 WPF 来保持安静。我知道 WPF 中的 DataGrid 没有 Column 集合作为依赖属性,因此无法动态添加列。

我正在开发的应用程序是高度动态的,因此不知道列数。所以我正在从后面的代码中创建 DataGridTemplate 列。

问题 1:我希望交替列具有不同的背景颜色。我如何以编程方式进行操作? (DataGridTemplateColumn 没有 Background 属性,所以我无法找到解决方案)

问题 2:我的 DataGridTemplateColumn 有一个 DataTemplate,其中有一个 StackPanel,里面有 2 个 TextBox。 DataGrid 中有一个称为 CellEditing Event 的事件,它在我们编辑单元格时触发。它适用于默认列,但对于我的列,如果我编辑这些文本框,则事件不会被触发!!!那么我该如何实现呢??

(我有时会对 WPF 感到惊讶!!!)

【问题讨论】:

    标签: wpf datagrid background-color


    【解决方案1】:

    零问题如果您在设置数据网格时使用AutoGenerateColumns="true",您可以为您生成数据网格中的列。它以后不会动态添加列,但是如果您重置 itemssource 可能会? (对那个不积极)

    问题一 DataGrid 具有属性AlternatingRowBackgroundAlternationCount 来设置交替的 背景。但我看不到网格本身中交替列背景的任何内容。不过,您可以在数据模板中执行此操作:

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Background="Red" Foreground="White">I'm Red</TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    

    但即使margin=0,我仍然看到其中的边距,所以如果你使用任何非常明显的颜色,单元格看起来很有趣。

    问题二是指CellEndEditing 事件吗?因为我没有看到任何其他单元格编辑事件。我尝试了以下方法:

        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" CellEditEnding="DataGrid_CellEditEnding">
            <DataGrid.Columns>
                <DataGridTextColumn Header="A" Binding="{Binding Field0}" />
                <DataGridTemplateColumn Header="BC">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Field1}"/>
                                <TextBlock Text="{Binding Field2}" />
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBox Text="{Binding Field1}"/>
                                <TextBox Text="{Binding Field2}" />
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    

    每当 CellEditingTemplate 中的任何一个文本框失去焦点时,无论数据是否更改,我的 DataGrid_CellEditEnding 事件处理程序都会被调用,所以事情似乎对我有用。

    除了“内置”WPF 之外,您还使用其他 DataGrid 吗?

    【讨论】:

    • 问题 2 对我来说是非常重要的问题。我必须解决它,因为它是客户的要求。如果你找到了一些设置列颜色的方法,请告诉我!!!!
    • 我的 DataTemplate 包含一个 ComboBox 实例,用于 CellTemplate 和 CellEditingTemplate,其中 UpdateSourceTrigger 为 propertyChanged,但事件对此没有任何想法?
    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多