ListBox选择的项目事件
亲爱的,
我有一个基于列表框选定项目事件的基本问题。
I have a basic question based on a listbox selected items event.
当用户选择列表框时items,我需要在MVVM属性中获取所选项目以执行某些验证。
When a user select a listbox items, I need to get the selected items in a MVVM property in order to perform some validation.
捕获此事件的最佳方法是将选定项目列表传递给我MVVM?
What is the best way to catch this event and pass it the list of slected items to my MVVM ?
问候
你的知识会被其他人提升。
Your knowledge is enhanced by that of others.
如果它只是一个选定的项目,那么你可以绑定到一个viewmodel属性并在setter中放入一些代码。
If it was just one selected item then you can bind to a viewmodel property and put some code in the setter for that.
如果你想要多个selecteditemS,那么它可能会更复杂。
If you want multiple selecteditemS then it's potentially rather more complicated.
假设您正在绑定ObservableCollection< RowVM>到ItemsSource。
Say you're binding ObservableCollection<RowVM> to ItemsSource.
在RowVM上你可以公开一个IsSelected并绑定它。
On RowVM you can expose an IsSelected and bind that.
实际上我在app中有一个基本的viewmodel类我是工作:
In fact I have a base viewmodel class in an app I'm working on:
public class ListedItemViewModel : BaseValidViewModel
{
private bool isExpanded = false;
public bool IsExpanded
{
get { return isExpanded; }
set { isExpanded = value; RaisePropertyChanged(); }
}
private bool isSelected = false;
public bool IsSelected
{
get { return isSelected; }
set { isSelected = value; RaisePropertyChanged(); }
}
通过样式应用的绑定:
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
这很简单,但不能很好地涵盖所有用例。
Which is pretty simple but doesn't cover all use cases so well.
如果您需要在父视图模型中执行其中一项更改,那么这有点复杂。
If you need to do something in the parent viewmodel when one of those changes then that's a bit of a complication.
您可以将引用传递给RowVM新手时的父母。它可能是视图的viewmodel,它创建了所有的RowVM。然后,您可以根据您想要的任何条件从RowVM调用父视图模型上的公共方法。
You could pass a reference into the RowVM for the parent when you new it up. It's probably the view's viewmodel which creates all your RowVM. You can then call a public method on the parent viewmodel from RowVM based on whatever criteria you want.
使用的另一种方法是附加属性/行为。添加附加属性意味着您可以绑定到该属性并且行为可以重复使用。
Another approach used is an attached property/ behaviour. Adding an attached property means you can then bind to that and a behaviour is re-usable.
这是一个实现:
http:// blog .functionalfun.net / 2009/02 / how-to-databind-to-selecteditems.html
http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html