我很难绑定到使用itemsSource的树视图集合的集合。最终我在下面写了代码监听,但它仍然不起作用。XAML:绑定集合里面的集合
MainWindows.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="ButtonBase_OnClick"/>
<TreeView Name="TreeView" VerticalAlignment="Top">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<ItemsControl ItemsSource="{Binding Tuples}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Item1}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</StackPanel>
</Window>
而且MainWindows.xaml.cs:正确显示
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<Person> Col { get; set; }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var Trades = new ObservableCollection<Person>
{
new Person()
{
Tuples = new List<Tuple<string,string>>()
{
new Tuple<string, string>("Peter1", "Adam1"),
new Tuple<string, string>("Peter2", "Adam2"),
new Tuple<string, string>("Peter3", "Adam3")
},
Name = "MyName"
},
new Person()
{
Tuples = new List<Tuple<string,string>>()
{
new Tuple<string, string>("Peter1", "Adam1"),
new Tuple<string, string>("Peter2", "Adam2"),
new Tuple<string, string>("Peter3", "Adam3")
},
Name = "MyName2"
}
};
TreeView.ItemsSource = Trades; // Why it's not working ?
}
}
public class Person
{
public string Name { get; set; }
public IEnumerable<Tuple<string, string>> Tuples;
}
属性名称类别的人,但不显示在所有人的IEnumerable集合。我做错了什么?有没有更好的做法呢?如果可能的话,我希望代表代码最小化代码的大小。
你想要一个'TreeView'或一个嵌套的'ItemsControl'吗?在你的代码中,'TreeView'不是必需的,因为它只显示顶级项目。 – Koopakiller
您无法绑定元组列表。请参阅http://stackoverflow.com/questions/4017714/binding-to-a-list-of-tuples –