C# 如何将ObservableCurrentDictionary绑定到WPF TreeView

C# 如何将ObservableCurrentDictionary绑定到WPF TreeView,c#,wpf,xaml,data-binding,treeview,C#,Wpf,Xaml,Data Binding,Treeview,我正在尝试将Microsoft示例ObservableCurrentDictionary.cs对象绑定到树视图。我搜索了一些关于装订词典的例子,但尽管有很多例子,但似乎没有一个适合我。每当我运行它,屏幕上就会显示一个空的treeview,只有白色的轮廓。我已将代码精简到最低限度进行测试,我的实现如下: <Window x:Name="AppWindow" x:Class="ControlCenter.MainWindow" xmlns="http://schemas.microso

我正在尝试将Microsoft示例ObservableCurrentDictionary.cs对象绑定到树视图。我搜索了一些关于装订词典的例子,但尽管有很多例子,但似乎没有一个适合我。每当我运行它,屏幕上就会显示一个空的treeview,只有白色的轮廓。我已将代码精简到最低限度进行测试,我的实现如下:

<Window x:Name="AppWindow" x:Class="ControlCenter.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Control Center" Height="1000" Width="1200"
    WindowStartupLocation="CenterScreen">
<Grid x:Name="left_grid" Margin="362,199,551,237">
    <TreeView ItemsSource="{Binding _hostList}">
        <TreeView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding _hostList.Values}"/>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>
<TreeView ItemsSource="{Binding}">
    <TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Values}"/>
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

}有几个问题。首先,因为您没有在绑定中指定源,所以它将脱离DataContext,而DataContext为null

我想您是在想,既然您使用的是MainWindow,那么绑定语句的源将是MainWindow对象,但这不是绑定的默认值。如果您想这样做,您必须在绑定中使用RelativeSource,但通常您只是将集合作为视图模型的一部分或直接作为整个视图模型弹出到DataContext中。大概是这样的:

public ObservableConcurrentDictionary<string, string> _hostList = new ObservableConcurrentDictionary<string, string>();
public MainWindow()
{
    InitializeComponent();
    _hostList.Add("TestHost1", "Host1");
    _hostList.Add("TestHost2", "Host2");
    _hostList.Add("TestHost3", "Host3");
    DataContext = _hostList;
} 
我想这并不能完全解决您的问题,因为我认为您绑定到了错误的属性。ItemsSource应该绑定到某种IEnumerable,而文本应该绑定到字符串


因此,我不确定您在理想情况下想要展示什么,但我非常确定您没有正确绑定。通常使用TreeView时,您将使用,我认为这可能是您想要使用的。

我认为问题在于您需要绑定到属性,而不是类型字符串。否则绑定将无法工作。具体地

 public ObservableConcurrentDictionary<string, string>...
有背景

  listBox.ItemsSource = _hostList;
你做了一个树,我用列表视图进行了测试 那么绑定应该是

{Binding Value.mystg}
我注意到,字典不支持排序,在我看来,新添加的条目是随机的,所以排序可能是另一种动物

       public class myobj {
            public string mystg { get; set; }
        }
  listBox.ItemsSource = _hostList;
{Binding Value.mystg}