我有一个KeyValuePair的可观察集合。我需要获取所选项目的密钥。
private ObservableCollection<KeyValuePair<String, Items>> _items;
<ListView Grid.Column="0" HorizontalAlignment="Stretch" Padding="5" ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedThings, Mode=TwoWay}" SelectedValuePath="Value" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center">
<Image Height="40" Source="Resources/Apps64.png"/>
<TextBlock MinWidth="120" HorizontalAlignment="Stretch" TextAlignment="Center" Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:1)
假设您的Items
集合是这样的:
private ObservableCollection<KeyValuePair<string,string>> _items = new ObservableCollection<KeyValuePair<string, string>>();
public ObservableCollection<KeyValuePair<string,string>> Items
{
get
{
return _items;
}
set
{
if (_items == value)
{
return;
}
_items = value;
}
}
然后从viewModel获取SelectedItem
密钥,只需在视图模型中创建KeyValuePaire
属性,然后将其绑定到ListView
SelectedItem
private KeyValuePair<string,string> _selectedItem ;
public KeyValuePair<string,string> SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem.Equals(value))
{
return;
}
_selectedItem = value;
}
}
selectedItem
要获取Xaml中ElementName
的密钥,只需使用Binding
ListView
SelectedItem
<ListView x:Name="Lv" Grid.Column="0" HorizontalAlignment="Stretch" Padding="5" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" SelectedValue="{Binding SelectedThings, Mode=TwoWay}" SelectedValuePath="Value" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center">
<Image Height="40" Source="Resources/Apps64.png"/>
<TextBlock MinWidth="120" HorizontalAlignment="Stretch" TextAlignment="Center" Text="{Binding ElementName=Lv,Path=SelectedItem.Key}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
:
response