首页 文章

来自treeview控件的绑定错误

提问于
浏览
2

我遇到了一个问题,如果你能为此提供任何建议,我将非常感激 .

错误信息:

System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'' . BindingExpression:路径= HorizontalContentAlignment;的DataItem = NULL; target元素是'TreeViewItem'(Name =''); target属性是'HorizontalContentAlignment'(类型'HorizontalAlignment')

我有一个treeview控件(C#WPF .NET 4.0),通过在xaml中使用datatemplate或手动将几个项添加到此树视图中,并且两者都使用数据绑定 .

当收到新的数据结构时,我需要清理treeview中的所有项目并通过 treeview_Control.Items.Clear() 重新生成新项目,从GUI的角度来看似乎工作正常,但是当我在Visual Studio上看到输出窗口时,它会显示几条错误消息,如上所示 .

我试图寻找解决方案并尝试了几种方法,但还没有运气 . 有人刚建议忽略这个错误信息,但我真的想清除它 .

如果您有任何想法,请帮助我 .

2 回答

  • 3

    对不起,这是评论,但我不能在评论部分

    你可以尝试在TreeView上添加 ItemContainerStyle 并查看它是否修复了错误,我们在 ListView 中遇到了同样的问题,这是我们可以找到的唯一解决方法来消除错误 .

    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
        </Style>
    </TreeView.ItemContainerStyle>
    
  • 0

    我有同样的问题 . 当我通过ViewModel从treeview中删除项目时,我收到了同样无害的错误消息 . 我在UserControl.Resources中为TreeViewItem定义了样式 . 在该风格中也是用于内容对齐的设置器 .

    <Style TargetType="TreeViewItem" x:Key="myTreeViewItemStyle"
                 BasedOn="{StaticResource {x:Type TreeViewItem}}">
                <Setter Property="HorizontalContentAlignment"
                        Value="Left" />
                <Setter Property="VerticalContentAlignment" Value="Center"/>
        ...</Style>
    

    对我有帮助的是TreeView中的addint ItemContainerStyle referenc .

    <TreeView ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource ResourceKey=myTreeViewItemStyle}">
    

相关问题