在WPF中为ComboBox
绑定命令通常涉及ICommand
接口的实现及XAML中事件与命令的关联。以下是具体实现方式:
<!-- 引用行为命名空间 -->
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
注意用 2010的版本
命令绑定和参数
<ComboBox Grid.Row="0" x:Name="cboFormulaList" Width="100" Height="25" FontSize="15" Margin="5,10,0,6" HorizontalAlignment="Left" VerticalAlignment="Center"
ItemsSource="{Binding FormulaList}"
DisplayMemberPath="Name"
SelectedValuePath="Id"
SelectedItem="{Binding FormulaSelect, Mode=TwoWay}"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding FormulaSelectionChangedCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
ViewModel
/// <summary>
/// 选择 配方
/// </summary>
public RelayCommand<object> FormulaSelectionChangedCommand
{
get
{
return new RelayCommand<object>((arg) =>
{
//var content = arg.Content.ToString();
//var id = arg;
if (arg is ComboBox)
{
var val = (arg as ComboBox).SelectedValue;
FormulaSelect = FormulaList.First(t => t.Id == val.ToInt());
if (FormulaSelect != null)
{
SearchModel.FormulaId = FormulaSelect.Id;
}
this.Query();
}
});
}
}