【问题标题】:How can I extend a ComboBox to support commands (MVVM)?如何扩展 ComboBox 以支持命令 (MVVM)?
【发布时间】:2011-02-24 05:07:18
【问题描述】:
正如主题所说,我需要扩展标准 Silverlight ComboBox 的功能以支持命令。由于我遵循 MVVM,因此我需要我的 ComboBox 将 SelectionChanged 事件传达给我的 ViewModel。
执行此操作的代码会是什么样子?我希望能够将 Command 属性放在我的 ComboBox XAML 控件上。
使用(WCF RIA、MVVM、VB.NET)..
所有提示都已应用!
【问题讨论】:
标签:
vb.net
silverlight
mvvm
combobox
command
【解决方案1】:
创建一个公开ICommand Command 和object CommandParameter 的行为。在行为连接到 AssociatedObject 的 SelectionChanged 事件。然后您可以将命令绑定到您的行为并为 SelectionChanged 事件模拟命令。
【解决方案2】:
您可以将 Combobox 的 SelectedIndex 或 SelectedItem 属性绑定到您的 ViewModel。所以你不需要任何命令。
示例(绑定到 SelectedIndex):
XAML
<ComboBox SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"/>
C#
public class ComboBoxViewModel
{
private int _selectedIndex;
public int SelectedIndex {
get { return _selectedIndex; }
set {
if (value != _selectedIndex) {
_selectedIndex = value;
// Perform any logic, when the SelectedIndex changes (aka. PropertyChanged-Notification)
}
}
}
}
示例(绑定到 SelectedItem):
XAML
<ComboBox SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/>
C#
public class ComboBoxViewModel
{
private MyViewModel _selectedItem;
public MyViewModel SelectedItem {
get { return _selectedItem; }
set {
if (value != _selectedItem) {
_selectedItem= value;
// Perform any logic, when the SelectedIndex changes ((aka. PropertyChanged-Notification)
}
}
}
}