选择键作为列表视图中的SelectedItems
本文关键字:SelectedItems 视图 列表 选择 | 更新日期: 2023-09-27 18:11:34
我有一个字典绑定到ListView,并有两个列。它支持多重选择和一个Ok按钮。现在从listview中选择项目后,我只希望第一列即字典的键保存在列表list1中。需要帮助:)
后端代码:-
public partial class MainWindow : Window
{
public List<string> list1
{
get;
set;
}
public MainWindow()
{
InitializeComponent();
Dictionary<int, string> list = new Dictionary<int, string>();
list.Add(1, "a");
list.Add(2, "b");
lvUsers.ItemsSource = list;
lvUsers.SelectedIndex = 0;
}
public void getSelectedItem(Object sender, RoutedEventArgs e)
{
// Here is the part where you get the keys of selected items
}
}
}
Xaml代码:-<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListView Margin="10,10,10,0" Name="lvUsers" SelectionMode="Multiple" Grid.Row="0">
<ListView.View>
<GridView>
<GridViewColumn Header="column1" Width="120" DisplayMemberBinding="{Binding Key}" />
<GridViewColumn Header="column2" Width="50" DisplayMemberBinding="{Binding Value}" />
</GridView>
</ListView.View>
</ListView>
<Button x:Name="getitem" Click="getSelectedItem" Grid.Row="1" Content="ok" />
</Button>
</Grid>
</Window>
类似这样的代码应该可以达到这个效果:
var keys = lvUsers.SelectedItems.OfType<KeyValuePair<int, string>>().Select(x => x.Key);
首先,你在使用terms
,而你并没有真正这样做。
WPF
中的Binding
使用{Binding}
语法或Binding
类。你基本上只是设置了给定字典的ItemsSource
。
因为你没有遵循MVVM
模式,只是在代码后面做。您可以使用LINQ
list1
list1 = lvUsers.SelectedItems.OfType<KeyValuePair<int,string>>().Select(x => x.Key.ToString()).ToList();
您可以在Name属性中找到关键字:
string MyKey = MyListView.SelectedItems[0].Name;
显示如下:
private void MyListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListView.SelectedItems.Count != 0)
{
string MyKey = MyListView.SelectedItems[0].Name;
//...
}
}