Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - Can't set Foreground color in DataGrid using Binding

I'm working with a DataGrid in a Windows UWP application.

I'm trying to set the Foreground property of a DataGridTextColumn by binding it to a color value in my model. My model object has a property, called Color, that returns a value of type Windows.UI.Xaml.Media.Brush. As this is the same type as the Foreground property, I assumed I could set it directly, like this:

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

However, this results in a runtime exception that says, "Failed to assign property".

I have seen code samples that appear to be doing the same thing, and I'm struggling to understand why this won't work.

question from:https://stackoverflow.com/questions/65948376/cant-set-foreground-color-in-datagrid-using-binding

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Referring to the document, we know that a property must be a dependency property to be the target of a {Binding} markup extension, but {x:Bind} does not have this requirement as it uses generated code to apply its binding values. From the code of Foreground of DataGridTextColumn, the Foreground property is not a dependency property, therefore it is not supported to do the data binding by {Binding} extension for the Foreground property.

You could custom a CellTemplate to set a data binding for the Foreground property for a DataGridTemplateColumn instance.

For example:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...