wpf listbox中添加checkbox实现多选,listbox绑定的数据源是list<string>,并将选中的值传入后台,使用mvvm模型,给出示例代码
时间: 2023-04-04 17:02:06 浏览: 222
可以使用以下代码实现:
在 XAML 中:
<ListBox ItemsSource="{Binding MyList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected}" />
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在 ViewModel 中:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private List<MyItem> _myList;
public List<MyItem> MyList
{
get { return _myList; }
set
{
_myList = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyList)));
}
}
public ICommand SaveCommand { get; }
public MyViewModel()
{
MyList = new List<MyItem>
{
new MyItem { Text = "Item 1" },
new MyItem { Text = "Item 2" },
new MyItem { Text = "Item 3" }
};
SaveCommand = new RelayCommand(Save);
}
private void Save()
{
var selectedItems = MyList.Where(x => x.IsSelected).Select(x => x.Text);
// 将选中的值传入后台
}
}
public class MyItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
}
}
public string Text { get; set; }
}
其中,RelayCommand 是一个实现了 ICommand 接口的类,用于绑定按钮的 Command 属性。
阅读全文