下載app免費領取會員
WPF 的ListBox 可以綁定SelectedItem但是不可以綁定SelectedItems不能綁定,這就有點煩了。
所以可以自定義一個依賴屬性來綁定:
首先定義個TListBox類來代替ListBox
public class TListBox:ListBox
{
public static readonly DependencyProperty SelectItemsProperty;
public List<ListBoxData> SelectItems
{
get
{
return (List<ListBoxData>)GetValue(SelectItemsProperty);
}
set
{
SetValue(SelectItemsProperty, value);
}
}
static TListBox()
{
SelectItemsProperty = DependencyProperty.Register("SelectItems", typeof(List<ListBoxData>), typeof(TListBox));//, data);
}
public TListBox()
{
this.SelectionChanged += TListBox_SelectionChanged;
}
private void TListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<ListBoxData> _items = new List<ListBoxData>();
TListBox box = sender as TListBox;
foreach(var itm in box.SelectedItems)
{
_items.Add(itm as ListBoxData);
}
SelectItems = _items;
}
}
創(chuàng)建ViewModel
public class ViewModel:INotifyPropertyChanged
{
private string _text = "1234";
public string Text
{
get
{
return _text;
}
set
{
_text = value;
RaisePropertyChanged(nameof(Text));
}
}
private List<ListBoxData> selectdatas = null;
public List<ListBoxData> SelectDatas
{
get
{
return selectdatas;
}
set
{
selectdatas = value;
RaisePropertyChanged(nameof(SelectDatas));
}
}
private List<ListBoxData> datas = null;
public List<ListBoxData> Datas
{
get
{
return datas;
}
set
{
datas = value;
RaisePropertyChanged(nameof(Datas));
}
}
public ViewModel()
{
datas = new List<ListBoxData>();
datas.Add(new ListBoxData(0, "name1"));
datas.Add(new ListBoxData(1, "name2"));
datas.Add(new ListBoxData(2, "name3"));
datas.Add(new ListBoxData(3, "name4"));
datas.Add(new ListBoxData(4, "name5"));
datas.Add(new ListBoxData(5, "name6"));
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string name)
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
public class ListBoxData
{
public int Id { get; set; }
public string Name { get; set; }
public ListBoxData(int id ,string name)
{
Id = id;
Name = name;
}
}
使用TListBox
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="411,277,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<local:TListBox x:Name="listBox" ItemsSource="{Binding Path=Datas}" DisplayMemberPath="Name"
SelectItems="{Binding Path=SelectDatas,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
HorizontalAlignment="Left" Height="188" Margin="38,22,0,0" VerticalAlignment="Top" Width="162" SelectionMode="Extended"/>
</Grid>
在Button的Click里驗證:
private void button_Click(object sender, RoutedEventArgs e)
{
string info = null;
foreach (var v in vm.SelectDatas)
{
info += v.Name + "\n";
}
MessageBox.Show(info);
}
本文版權歸腿腿教學網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權,謝絕轉載。