【问题标题】:Bind DataGridColumns Header to DataContext of the window将 DataGridColumns Header 绑定到窗口的 DataContext
【发布时间】:2016-03-08 03:48:53
【问题描述】:

我有一个DataGrid 并想将Header-property 绑定到我的窗口DataContext 的属性,但我没有让它工作。

绑定可能很痛苦,因为(对我来说)在简单地使用Binding 时,永远不清楚this 具有哪个上下文。 我知道Binding={} 中的“上下文”是DataGrids ItemsSource 的单个元素。但是Header={Binding ???} 的“上下文”是什么?

我已经试过了:

Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource Self}}
Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource TemplatedParent}}
Header="{Binding Path=DataContext.MyProperty, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyWindow}}}
Header="{Binding Path=DataContext.MyProperty, ElementName=MyWindowName}

我尝试了使用和不使用 Path,但没有任何效果。

例如,使用带有ElementName 的最后一个我得到以下绑定异常:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DataContext.MyProperty; DataItem=null; target element is 'DataGridTextColumn' (HashCode=51072575); target property is 'Header' (type 'Object')

是否有任何工具可以在运行时检查/更改绑定?甚至想知道当前的“上下文”是什么?

注意:DataGrid 在 Mahapps.Flyout 内(不确定这是否有什么要说的)。

【问题讨论】:

  • 我使用 Snoop 在运行时查看我的 DataContext 和绑定错误

标签: c# wpf xaml binding datagrid


【解决方案1】:

由于DataGridTextColumn 或任何其他受支持的数据网格列不属于datagrid 的可视化树,因此它们不会继承datagridDataContext。因为,它们不在可视化树中,所以任何尝试使用 RelativeSource 获取 DataContext 的方法都行不通。

解决方案——可以创建一个代理元素来绑定window/control的数据上下文;使用该代理元素绑定DataGridTextColumn 的标头。

<Grid>
   <Grid.Resources>
       <FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
   </Grid.Resources>
       <ContentControl Visibility="Collapsed" Content="{StaticResource ProxyElement}"></ContentControl>
       <DataGrid  
                       ItemsSource="{Binding Collection}" 
                       AutoGenerateColumns="False">
          <DataGrid.Columns>
              <DataGridTextColumn Header="{Binding DataContext.MyProperty, Source={StaticResource ProxyElement}}" Binding="{Binding PropertyName}" />
          </DataGrid.Columns>
     </DataGrid>
</Grid>

【讨论】:

  • 谢谢。这就是我永远不会喜欢Bindings 的原因之一。另一方面,为什么this 工作?
  • ProxyElement 是一个FrameworkElement,它从主视图中窃取DataContext 并将其提供给逻辑子视图,例如DataGridTextColumn。为此,它必须作为内容托管到同一视图下的不可见 ContentControl 中。
  • 不确定link 中提到的答案是否有效。
  • 确实它在工作并且(对我而言)它比使用代理更简单(并且可读性更好)。但这只是我的看法。
猜你喜欢
  • 1970-01-01
  • 2014-12-09
  • 2012-09-05
  • 2011-05-19
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多