如何获得所选Observable Collection的Key?

时间:2016-01-25 09:07:55

标签: c# wpf data-binding observablecollection

我有一个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>

1 个答案:

答案 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