【问题标题】:Databinding a Color in WPF DataTemplate在 WPF DataTemplate 中对颜色进行数据绑定
【发布时间】:2011-10-10 21:56:51
【问题描述】:

这个问题困扰了我一段时间,我似乎无法让它工作。我正在使用数据模板来格式化 ListBox 控件中的项目,如下所示:

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

问题是矩形没有像它应该的那样显示为绑定颜色。跟踪转换器,绑定似乎从绑定项目中正确获取颜色(复选框和标签上的其他绑定按预期工作)。我在调试输出中也没有发现绑定错误。

我还尝试将矩形包装在带有黑色边框的 &lt;border&gt; 元素中,它显示正确,所以我知道矩形至少显示出来了,但是用矩形 @ 的相同绑定替换 BorderBrush 属性如上所示的 987654324@ 属性导致边框消失(同样,没有绑定错误)。

如何正确实现 WPF 中颜色的绑定?

【问题讨论】:

  • 我假设 SolidColorBrushConverter 已经将输入值转换为正确的 Brush 实例?

标签: c# wpf xaml data-binding datatemplate


【解决方案1】:

该代码没有问题,故障必须与转换器有关。也许它得到了颜色,但将 alpha 通道设置为 0,使所有颜色完全透明。如果不是这样,您应该发布转换器的代码,以便人们可以查看它。

您也可以在没有任何转换器的情况下轻松获得:

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

【讨论】:

  • 我最初试图按照你说的那样做,没有转换器,但转换器至少允许我查看传递的值。不透明是问题所在。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多