【发布时间】:2023-04-04 02:06:01
【问题描述】:
我有以下 xaml 代码:
<ListBox Foreground="{Binding MyColor, Converter={local:ColorConverter}}" ItemsSource="{Binding LogCollection, Mode=TwoWay}" Grid.Row="1">
</ListBox>
这会改变整个列表框的前景色,所以我这样修改代码:
<ListBox ItemsSource="{Binding LogCollection, Mode=TwoWay}" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{Binding MyColor, Converter={local:ColorConverter}}" Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
通过这种方式,我想为一个项目而不是为整个列表框设置前景,但它不起作用。如何找到正确的数据上下文? MyColor 是 MainViewModel 上的一个属性。
稍后使用解决方案进行编辑
Jens 的回答让我明白了我的错误所在。我没有在 ObservableCollection 中存储简单的消息日志字符串,而是创建了一个包含 Message 和 Color 成员的新类 (LogItems)。现在 LogCollection 是 LogItems 类型而不是字符串。
我在视图模型中使用以下代码填充列表框:
LogItems logitem = new LogItems(myMessage, myColor);
LogCollection.Insert(0, logitem);
并且视图具有以下形式。也不再需要使用RelativeSource,因为datacontext是一样的。
<ListBox ItemsSource="{Binding LogCollection, Mode=TwoWay}" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{Binding Path=Color, Converter={local:ColorConverter}}" Text="{Binding Path=Message}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
感谢大家的回答,让我找到了这个解决方案。
【问题讨论】:
标签: wpf binding datacontext textblock