我有一本字典<字符串,字符串[]>。我已经将键绑定到了一个组合框,但我遇到了一个阻止程序,试图将字符串数组绑定到一个列表视图,该列表视图将根据选择的键动态更新。我能够将第一个数组绑定到列表视图,但我不确定我缺少了什么来让视图在键之间切换-
型号-
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
ViewModel-
public class ViewModel
{
private Dictionary<Person, string[]> _person;
public Dictionary<Person, string[]> Persons
{
get { return _person; }
set { _person = value; }
}
private int _selectedPersonIndex;
public int SelectedPersonIndex
{
get { return _selectedPersonIndex; }
set
{
_selectedPersonIndex = value;
}
}
public ViewModel()
{
Persons = new Dictionary<Person, string[]>();
Persons.Add(new Person() { Name = "Mark" }, new string[] { "shirt", "pants", "shoes" });
Persons.Add(new Person() { Name = "Sally" }, new string[] { "blouse", "skirt", "boots", "hat" });
}
}
XAML-
<Window x:Class="MVVM_Combobox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewmodel="clr-namespace:MVVM_Combobox.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>
</Window.Resources>
<StackPanel Orientation="Vertical" DataContext="{Binding Source={StaticResource vm}}">
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
x:Name="cmbTest"
ItemsSource="{Binding Path=Persons.Keys}"
SelectedValue="{Binding Path=SelectedPersonIndex}"
DisplayMemberPath="Name"/>
<ListView ItemsSource="{Binding Path=Persons.Values/}"
x:Name="myListView">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource AncestorType=ListViewItem}}"/>
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Window>
通过添加
<ListView ItemsSource="{Binding Path=Persons.Values/}"
它甚至在从组合框中选择密钥之前就可以获得第一个密钥的数组值
您应该不将ComboBox绑定到Persons.Keys
,而仅绑定到Persons
。这意味着DataTemplate
的DataType
是KeyValuePair<Person, string[]>>
。
如果您只是想在ComboxBox中查看Key值,那么请使用DisplayMemberPath
属性。这将告诉WPF在UI中显示所选项目的哪个元素。您将需要一个"视图"模型属性来跟踪当前选定的项目。像这样:
<ComboBox ItemsSource="{Binding Persons}"
DisplayMemberPath="Key.Name" />
但这还不够。您还需要在详细信息视图中查看字符串数组中的所有项。在这种情况下,您需要视图模型来跟踪当前选定的项目。像这样:
<ComboBox ItemsSource="{Binding Persons}"
DisplayMemberPath="Key.Name"
SelectedItem="{Binding SelectedItem}"/>
支持视图模型属性将再次为相同的KeyValuePair类型。像这样:
private KeyValuePair<Person, string[]> _selectedItem;
public KeyValuePair<Person, string[]> SelectedItem
{
get => _selectedItem;
set => SetField(ref _selectedItem, value);
}
然后,您希望您的ListView(详细信息视图(绑定到当前所选项目的数组。由于该项是KeyValuePair
,因此它需要绑定到Value
,如下所示。
<ListViewItemsSource="{Binding SelectedItem.Value}"