【问题标题】:Get parent datacontext brush from inside a listview从列表视图中获取父数据上下文画笔
【发布时间】:2014-07-02 22:15:23
【问题描述】:

我得到了以下信息:

<ListView ItemsSource="{Binding Path=Items}">                        
     <ListView.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=GridTextColor}"></TextBlock>
         </DataTemplate>
     </ListView.ItemTemplate>
</ListView>

数据上下文如下所示:

class{
 items = List with items (each row has a name property)
 GridTextColor = Brush
}

我将列表视图与所有项目绑定。每个项目都包含一个名称,并且该名称很好地显示在列表视图中。

问题是我希望 DataTemplate 中的所有项目都将 Foreground 设置为画笔。 使用上面的代码是不可能的,因为当我在 DataTemplate 中时,我绑定到发送的项目。 问题,如何绑定到“父数据上下文”以获得正确的前景色?

【问题讨论】:

    标签: c# wpf binding wpf-controls


    【解决方案1】:

    您可以在绑定中使用 RelativeSource 来获取父级的 DataContext。

    <TextBlock Text="{Binding Path=Name}"
               Foreground="{Binding Path=DataContext.GridTextColor,
                                   RelativeSource={RelativeSource Mode=FindAncestor, 
                                                         AncestorType=ListView}}"/>
    

    或在 ListView 上设置 x:Name 并使用 ElementName 进行绑定:

    <ListView x:Name="myListView">
       ....
         <TextBlock Text="{Binding Path=Name}"
                    Foreground="{Binding DataContext.GridTextColor,
                                         ElementName=myListView}" />
       ....
    </ListView>
    

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 2017-05-16
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多