【问题标题】:Can't set Foreground color in DataGrid using Binding无法使用绑定在 DataGrid 中设置前景色
【发布时间】:2021-01-29 03:25:53
【问题描述】:

我正在 Windows UWP 应用程序中使用 DataGrid。

我正在尝试通过将 DataGridTextColumn 绑定到我的模型中的颜色值来设置它的 Foreground 属性。我的模型对象有一个名为 Color 的属性,它返回 Windows.UI.Xaml.Media.Brush 类型的值。由于这与 Foreground 属性的类型相同,我假设我可以直接设置它,如下所示:

<DataGridTextColumn Foreground="{Binding Path=Color}" ...

但是,这会导致运行时异常,提示“无法分配属性”。

我看到的代码示例似乎在做同样的事情,我很难理解为什么这不起作用。

【问题讨论】:

  • 请发布所有用于绑定的代码。
  • msdn好像只接受xaml中的字符串
  • 你是说 Foreground 属性需要一个字符串吗?我会在这个字符串中放什么?
  • 我尝试使用诸如“Red”或“Blue”之类的字符串值。我犯了同样的错误。如果我将它们逐字输入 xaml 文件,这些值确实有效,但不使用 Binding。
  • 我也试过使用转换器;同样的错误,我的转换器代码甚至从未被调用。这非常令人困惑。我在其他地方使用转换器来设置颜色没有问题。

标签: c# uwp uwp-xaml


【解决方案1】:

参考document,我们知道属性必须是依赖属性才能成为{Binding}标记扩展的目标,但是{x:Bind} 没有此要求,因为它使用生成的代码来应用其绑定值。从ForegroundDataGridTextColumncode 来看,Foreground 属性不是依赖属性,因此不支持通过{Binding} 扩展对Foreground 属性进行数据绑定。

您可以自定义CellTemplate 来为DataGridTemplateColumn 实例的Foreground 属性设置数据绑定。

例如:

<controls:DataGrid.Columns>
    <controls:DataGridTemplateColumn Header="header">
        <controls:DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate x:DataType="local:Customer">
                <StackPanel >
                //MyBrush is a SolidColorBrush in Customer class, adjust it for your scenario
                    <TextBlock Text="{x:Bind FirstName}" Foreground="{x:Bind MyBrush}"/>  
                </StackPanel>
            </DataTemplate>
        </controls:DataGridTemplateColumn.CellEditingTemplate>
    </controls:DataGridTemplateColumn>

【讨论】:

  • 谢谢,这为我解决了问题。我设法使用您的示例的变体获得了我想要的东西,但是为每个单元格执行此操作需要做很多工作,所以我可能会在没有它的情况下生活。
【解决方案2】:

不幸的是,这个问题仍然困扰着我。

我以为我已经设法动态设置了行颜色,但结果发现我选择的动态颜色与默认颜色相同,当我更改它时,什么也没发生。

所以我还在寻找解决方案。

我有很多专栏。对于我来说,实现一个需要粘贴 10 多行 XML 数十次的解决方案是不可行的。

难道没有办法在代码中做到这一点吗?我可以以某种方式抓取包含文本的 UI 元素并对其进行修改吗?

这是我正在做的一个例子。 TextWrapping 和 TextAlignment 设置有效,但 Foreground 设置不起作用,即使我为其分配了一个常量值。

                <controls:DataGridTextColumn x:Name="notesCol" Binding="{Binding Notes, Mode=OneWay}" MaxWidth="500" Header="Notes" Tag="Notes">
                <controls:DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Setter Property="TextBlock.TextWrapping" Value="Wrap" />
                        <Setter Property="TextBlock.TextAlignment" Value="Left"/>
                        <Setter Property="TextBlock.Foreground" Value="Green"/>
                    </Style>
                </controls:DataGridTextColumn.ElementStyle>
            </controls:DataGridTextColumn>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2018-05-19
    • 2016-03-03
    • 2011-03-08
    • 1970-01-01
    相关资源
    最近更新 更多