【问题标题】:Binding in listbox with textblocks not working在列表框中绑定文本块不起作用
【发布时间】: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


    【解决方案1】:

    列表框中生成的容器的 DataContext 会自动设置为相应的项,因此您的 Binding 没有找到 Property MyColor。您需要使用 RelativeSource 绑定来绑定到包含列表的 DataContext:

    <TextBlock Foreground="{Binding DataContext.MyColor, 
                                    RelativeSource={RelativeSource 
                                            Mode=FindAncestor, 
                                            AncestorType={x:Type ListBox}}, 
                                    Converter={local:ColorConverter}}"  
               Text="{Binding}"/>
    

    【讨论】:

    • 绑定现在有效。不幸的是,前景适用于整个列表框项目,而不仅仅是一项。我试着把它改成ListView,结果一样。
    • 你想达到什么目的?如果每个项目都应该有自己的颜色,则应该在 LogCollection 中的项目上引入 MyColor 属性。否则:应该为哪个项目着色?
    猜你喜欢
    • 2015-01-29
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多