我在这个机智的结尾...所以我有一个经典的产品类别场景。产品属于一个类别。我的列表框源代码是产品,每个产品都会有一个类别的组合框。我的问题是,SelectionChanged似乎并没有触发。所有数据都显示正常。组合框加载罚款等不知道如何调试这个.. .......列表框中Combobox的事件处理(使用数据绑定)
<DataTemplate x:Key="ProductDataTemplate">
<StackPanel Orientation="vertical">
//resources here...
<TextBlock Text="{Binding Path=ProductName}" ></TextBlock>
<ComboBox Background="Transparent" SelectedValuePath="CategoryId" DisplayMemberPath="CategoryName" SelectedIndex="0">
<ComboBox.ItemsSource>
<CompositeCollection>
<models:Category CategoryName="Select" CategoryId="{x:Static sys:Guid.Empty}" Order="0"/>
<CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=categories}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding Path=SelectionChangedCommand}" CommandParameter="{Binding SelectedItem}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</StackPanel>
和我的列表框其他地方是:
<ListBox ItemsSource="{Binding Products}" ItemTemplate="{DynamicResource ProductDataTemplate}" Height="Auto" Margin="50,256,50,64" HorizontalAlignment="Center">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
和我的视图模型是标准的东西:
public ICommand SetSelectionChangedCommand { get { return new RelayCommand(param => this.SetSelectionChangedExecute(param), null); } }
private void SetSelectionChangedExecute(object param)
{
MessageBox.Show("Selected");
}
什么是我有什么问题..为什么不控制来处理器时,我选择随机产品的随机类别?下面我RelayCommand:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
}
编辑: 我有一种感觉我的问题是命令绑定路径是不正确的。它如何知道去查看ViewModel?我的ViewModel被设置为一个祖先网格的DataContext,它在层次结构中处于领先地位。够了吗?或者,我要好好地限定在命令中的路径绑定?:
<i:InvokeCommandAction Command="{Binding Path=SelectionChangedCommand}" CommandParameter="{Binding SelectedItem}"></i:InvokeCommandAction>
什么我必须做,以确保命令中搜索在我的ViewModel?
我试过同在一个示例应用程序,它似乎工作的罚款。你可以从'RelayCommand'发布'ICommand.CanExecute'代码吗? – sthotakura
@sthotakura问题用RelayCommand更新。在其他地方,命令都可以正常工作。但不是在这里.. – Brian
代码看起来对我来说还行。 – sthotakura