【问题标题】:DataGridTextColumn header binding issue within a TabItem/TabControlTabItem/TabControl 中的 DataGridTextColumn 标题绑定问题
【发布时间】:2013-06-22 20:20:49
【问题描述】:

我似乎在尝试绑定 DataGridTextColumn 的标题列时遇到问题。当我没有包装它的 TabControl/TabItem 时,此代码工作正常,但是当我将它放在 TabControl 中时,它再也找不到 DayHeader。我想这是 FindAncestor/AncestoryType 的问题,但我不确定该怎么做才能修复它,或者这是否真的是问题所在。任何帮助将不胜感激。

<!--Not Working
<TabControl Margin="0,25,0,0" Background="{x:Null}">
    <TabItem >
        <Grid >
            <DataGrid></DataGrid>
        </Grid>
    </TabItem>
    <TabItem Header="Test Header">-->

<!--Working-->
<Grid>
    <DataGrid ItemsSource="{Binding RunningViewSource.View}" Margin="0,27,0,-5" SelectionMode="Single">
        <DataGrid.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel VirtualizingStackPanel.VirtualizationMode="Recycling" />
            </ItemsPanelTemplate>
         </DataGrid.ItemsPanel>
         <DataGrid.Columns>
             <DataGridTextColumn Header="Contingencies" Binding="{Binding Contingencies}"
                                            IsReadOnly="True" Width="400" />
             <DataGridTextColumn Binding="{Binding Days[4]}" CellStyle="{StaticResource NumberCell}">
                 <DataGridTextColumn.Header>
                     <TextBlock Text="{Binding DataContext.DayHeader, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}">
                     </TextBlock>
                  </DataGridTextColumn.Header>
             </DataGridTextColumn>
         </DataGrid.Columns>
     </DataGrid>
</Grid>

<!--Not Working
    </TabItem>
</TabControl>-->

这是我在添加非工作部件时在输出窗口中收到的消息。

System.Windows.Data 错误:4:找不到与引用'RelativeSource FindAncestor,AncestorType='System.Windows.Controls.DataGrid',AncestorLevel='1''的绑定源。 BindingExpression:Path=DataContext.DayHeader;数据项=空;目标元素是'TextBlock'(名称='');目标属性是“文本”(类型“字符串”)

编辑:当我有一个包含多个 TabItem 的 TabControl 时,我只能重现此错误。我已经更新了我的代码。抱歉有任何混淆,但添加其他 TabItem 是导致 DayHeader 无法访问的原因。

Edit2:我知道很多人使用 Snoop 来帮助他们解决绑定问题。好吧,当我用 Snoop 检查列标题时,当我突出显示它们时,文本会神奇地出现。我不知道为什么会这样,所以希望对 Snoop 有更多了解的人能够提供帮助。这是用于访问 DayHeader 的代码,也许会有所帮助。

//Code Behind
 private string dayHeader;

    public string DayHeader
    {
        get { return dayHeader; }
        set
        {
            dayHeader = value;
            NotifyOfPropertyChange(() => DayHeader);
        }
    }

感谢您的帮助。

【问题讨论】:

    标签: c# wpf mvvm binding snoop


    【解决方案1】:

    DataGridTextColumn.Header 不在可视化树中,因此它没有继承 DataContext。您可以使用Freezable 类,如this 文章中所示。

    【讨论】:

    • 谢谢。第一个建议是我已经尝试过的,但遗憾的是没有奏效。第二个建议给了我一个错误。由于循环依赖,无法调用 MarkupExtension.ProvideValue。 MarkupExtension 内的属性不能引用引用 MarkupExtension 结果的对象。受影响的 MarkupExtensions 是:System.Windows.Data.Binding
    • 我没有尝试过使用它,但我注意到如果我将第二个选项卡移动到第一个位置,一切都会正常显示。不知何故,当 tabitem 位于第二个位置时,datagrid 没有接收到更改之类的东西?
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多