简体   繁体   中英

Databinding a Color in WPF DataTemplate

This one has been bugging me for a while and I cant seem to get it to work. I am using a Data Template to format items within a ListBox control, like so:

<ListBox HorizontalAlignment="Stretch" Name="listBox1" VerticalAlignment="Stretch" Grid.ColumnSpan="3" Grid.Row="1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30" />
                    <ColumnDefinition Width="30" />
                    <ColumnDefinition Width="100*" />
                </Grid.ColumnDefinitions>
                <Rectangle Width="30" Height="10" Grid.Column="0" 
                    VerticalAlignment="Stretch" 
                    HorizontalAlignment="Stretch" 
                    Fill="{Binding Path=Color, 
                        Converter={StaticResource SolidColorBrushConverter}, 
                        Mode=OneWay}" />
                <CheckBox Grid.Column="1" 
                    VerticalAlignment="Center" 
                    HorizontalAlignment="Center" 
                    IsChecked="{Binding Path=Selected}" />
                <Label Grid.Column="2" VerticalAlignment="Center" 
                    Content="{Binding Path=Name}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The problem is that the rectangle does not appear with the bound color, as it should. Tracing the converter, the binding seems to get the color correctly from the bound item (the other bindings on the checkbox and the label work as expected). Also I get no binding errors in the debug output.

I also tried wrapping the rectangle in a <border> element with a black border, which shows correctly, so I know the rectangle is at least showing up, however replacing the BorderBrush attribute with the same binding from the rectangle's Fill attribute as shown above causes the border to disappear (again, with no binding errors).

How does one correctly achieve binding of a Color in WPF?

Nothing wrong with that code, the fault has to be with the converter. Maybe it gets the color but sets the alpha channel to 0, making all colors fully transparent. If that is not it you should post the code of the converter so people can have a look at it.

Also you can easily get by without any converters:

<Rectangle.Fill>
    <SolidColorBrush Color="{Binding Color}"/>
</Rectangle.Fill>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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