我有一個字典<string, string[]>。我已經將鍵系結到一個組合框,但是我遇到了一個阻止程式,試圖將字串陣列系結到一個串列視圖,該串列視圖將根據選擇的鍵進行動態更新。我能夠將第一個陣列系結到串列視圖,但我不確定我缺少什么來讓視圖在鍵之間切換 -
模型 -
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
視圖模型 -
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/}"
即使在從組合框中選擇鍵之前,它也會讓我獲得第一個鍵的陣列值
uj5u.com熱心網友回復:
您不應該將您的 ComboBox 系結Persons.Keys
到Persons
. 這意味著DataType
的DataTemplate
是KeyValuePair<Person, string[]>>
。
如果您只想查看 ComboxBox 中的 Key 值,請使用該DisplayMemberPath
屬性。這告訴 WPF 在 UI 中顯示所選專案的哪個元素。您將需要一個 View-model 屬性來跟蹤當前選定的專案。像這樣:
<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(詳細視圖)系結到當前所選專案的該陣列。由于該專案是 a KeyValuePair
,它需要系結到Value
,像這樣。
<ListViewItemsSource="{Binding SelectedItem.Value}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506366.html