你的 xaml 应该看起来像
<ListBox
ItemsSource="{Binding List}"
SelectedItem="{Binding Item}"/>
你的属性应该看起来像
private List<yourClass> list;
public List<yourClass> List
{
get { return list; }
set
{
list = value;
RaisPropertyChanged("List");
}
}
private yourClass item;
public yourClass Item
{
get { return item; }
set
{
item = value;
RaisPropertyChanged("Item");
}
}
现在您只需将 ViewModle 设置为 DataContext 并且有很多方法可以做到这一点
我使用一种非常简单的方法来创建一个 ResourceDictionary (VMViews.xaml)
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ProjectName.namespace"
xmlns:vw="clr-namespace:ProjectName.namespace" >
<DataTemplate DataType="{x:Type vm:YourVMName}">
<vw:YourVName/>
</DataTemplate>
</ResourceDictionary>
在我的 App.xaml 中
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Path/VMViews.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
编辑所选项目
(此代码未经测试)
XAML
<ListBox
ItemsSource="{Binding List}"
SelectedItem="{Binding Item}" SelectionChanged="ListBox_SelectionChanged">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.Resources>
</ListBox>
现在你的yourClass 需要实现IsSelected 属性
你可以做类似的事情
private yourClass item;
public yourClass Item
{
get { return item; }
set
{
item = value;
RaisPropertyChanged("Item");
SelectedItems = List.Where(listItem => listItem.IsSelected).ToList();
}
}
private List<yourClass> selectedItems;
public List<yourClass> SelectedItems
{
get { return selectedItems; }
set
{
selectedItems = value;
RaisPropertyChanged("SelectedItems");
}
}