我的列表框有问题 我已经将ListBox选择模式设置为Multiple 问题在于,Selected Item仅触发一次,而当我选择其他项时,它不会在视图模型上更改SelectedItem。 我确定选择了它们,因为在选择它们时我将属性绑定到true,但是所选项目不会更新。 例如: 可以说我有以下列表框: 一种 乙 C 选择A-> ViewModel将selectedItem更新为A 选择B-> ViewModel不会更新SelectedItem,但我可以看到选择了B 当我取消选择A时,ViewModel将SelectedItem更新为null 有人已经面临这个问题吗? 我的主要目标是使SelectedItem更新为我选择的 他是我的View代码:
<ListBox HorizontalAlignment="Center" ItemsSource="{Binding AvailableDagrVMEs}"
SelectedItem="{Binding SelectedDagrVME}"
SelectionMode="Multiple"
VirtualizingStackPanel.IsVirtualizing="False"
ScrollViewer.HorizontalScrollBarVisibility="Auto" Padding="0" Margin="0" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.PanningMode="HorizontalOnly"
Background="Transparent"
BorderThickness="0">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Taken, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<Image Source="{Binding Icon , Converter={StaticResource BitmapToImageSourceConverter}}"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
和ViewModel:
public BaseVME SelectedDagrVME
{
get { return selectedDagrVME; }
set
{
if (selectedDagrVME != value)
{
Set("SelectedDagrVME", ref selectedDagrVME, value);
}
}
}
我尝试过:TwoWay绑定/ UpdateTriggerSource
答案 0 :(得分:1)
由于您选择了Multiple
,因此SelectedItem
将始终是您选择中的第一个选择。要获取最后选择的项目,您必须注册SelectionChanged
事件并访问SelectedItems
属性,该属性包含您选择的所有项目。您可以使用某种行为来实现它,因为您可以重用它。
行为:
public class ListBoxSelection : Behavior<ListBox>
{
public static readonly DependencyProperty LastSelectedProperty = DependencyProperty.Register(nameof(LastSelected), typeof(object), typeof(ListBoxSelection), new PropertyMetadata(default(object)));
public object LastSelected
{
get
{
return (object)GetValue(LastSelectedProperty);
}
set
{
SetValue(LastSelectedProperty, value);
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//you can also use whatever logic if you evaluate e.RemovedItems and e.AddedItems
if ((AssociatedObject?.SelectedItems?.Count??0)>0)
{
LastSelected = AssociatedObject.SelectedItems[AssociatedObject.SelectedItems.Count-1];
}
else
{
LastSelected = null;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
}
}
XAML:
xmlns:i =“ clr-namespace:System.Windows.Interactivity; assembly = System.Windows.Interactivity” xmlns:b =“ clr-namespace:NameSpaceWhereBahaviorDefined”
<ListBox ...>
<i:Interaction.Behaviors>
<b:ListBoxSelection LastSelected = "{Binding VMSelection}" />
</i:Interaction.Behaviors>
</ListBox>