我有一个弹出窗口,里面有一个列表框控件。我需要将鼠标左键单击事件与列表框中的项目绑定。我已经写了
<Popup StaysOpen="False" IsOpen="{Binding VisibiltyAttr}" PlacementTarget="{Binding ElementName=InputText}" HorizontalAlignment="Center" AllowsTransparency="True" >
<ListBox ItemsSource="{Binding Collection}" SelectedIndex="{Binding Path=ItemIndex, Mode=TwoWay}" HorizontalAlignment="Center" VerticalAlignment="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox},
Path=DataContext.SelectionCommand}" CommandParameter="{Binding}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Popup>
在我添加弹出窗口之前,事件工作正常。
使用中继命令而不是委托命令
RelayCommand.cs
public class RelayCommand : ICommand
{
private Action<object> execute;
private Predicate<object> canExecute;
private event EventHandler CanExecuteChangedInternal;
public RelayCommand(Action<object> execute)
: this(execute, DefaultCanExecute)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException(nameof(execute));
}
if (canExecute == null)
{
throw new ArgumentNullException(nameof(canExecute));
}
this.execute = execute;
this.canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
CanExecuteChangedInternal += value;
}
remove
{
CommandManager.RequerySuggested -= value;
CanExecuteChangedInternal -= value;
}
}
public bool CanExecute(object parameter)
{
return canExecute != null && canExecute(parameter);
}
public void Execute(object parameter)
{
execute(parameter);
}
public void OnCanExecuteChanged()
{
EventHandler handler = CanExecuteChangedInternal;
handler?.Invoke(this, EventArgs.Empty);
}
public void Destroy()
{
canExecute = _ => false;
execute = _ => { };
}
private static bool DefaultCanExecute(object parameter)
{
return true;
}
}
YourViewModel.cs
private ICommand selectionCommand;
public ICommand SelectionCommand
{
get { return selectionCommand ?? (selectionCommand = new RelayCommand(Selected, CanSelect)); }
set { selectionCommand = value; }
}
private void Selected(object obj)
{
}