WPF -交互触发器在列表框中不工作

本文关键字:工作 列表 交互 触发器 WPF | 更新日期: 2023-09-27 18:09:01

我试图在WPF中添加一个SelectionChanged交互触发器到ListBox,以便我可以将事件路由到命令,但由于某种原因它不工作。

我的代码

<Border Background="Transparent">
  <ListBox Name="MyListBox"
           ScrollViewer.HorizontalScrollBarVisibility="Disabled"
           SelectedValue="A"
           SelectedValuePath="Content">
    <i:Interaction.Triggers>
      <i:EventTrigger EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding MyCommand}"
                               CommandParameter="{Binding ElementName=MyListBox, 
                                                          Path=SelectedIndex}" />
      </i:EventTrigger>
    </i:Interaction.Triggers>
    <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
        <WrapPanel IsItemsHost="True" />
      </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem>A</ListBoxItem>
    <ListBoxItem>B</ListBoxItem>
  </ListBox>
</Border>

我想我这里做错了什么

WPF -交互触发器在列表框中不工作

您的代码运行良好。你所需要的只是提供一个合适的视图模型,例如

注意:使用MVVM Light

public class TestViewModel : ObservableObject
{
    public TestViewModel()
    {
        this.MyCommand = new RelayCommand<int>(i => Debug.WriteLine(i));
    }
    public RelayCommand<int> MyCommand { get; private set; }
}

带硬编码视图模型的Xaml

<Window.DataContext>
    <my:TestViewModel/>
</Window.DataContext>
<Border Background="Transparent">
    <ListBox Name="MyListBox" 
    ... etc

您应该只将SelectedIndex绑定到DataContext中的属性,这将导致更简单的代码:

<Border Background="Transparent">
    <ListBox Name="MyListBox" 
             ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
             SelectedValue="A" SelectedValuePath="Content"
             SelectedIndex="{Binding MyIndexProperty}">
           <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
               <WrapPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem >A</ListBoxItem>
        <ListBoxItem >B</ListBoxItem>
    </ListBox>
</Border>
    // This is a property on a GalaSoft MVVMLIght ViewModel
    /// <summary>
    ///   ThemeInfo of the current active theme
    /// </summary>
    public String ActiveTheme
    {
        get
        {
            if (activeTheme == null)
            {
                activeTheme = Properties.Settings.Default.Default_App_Theme;
            }
            return activeTheme;
        }
        set
        {
            if (activeTheme == value)
            {
                return;
            }
            var oldValue = activeTheme;
            activeTheme = value;
            // Update bindings
            RaisePropertyChanged(ActiveThemePropertyName,    oldValue, value, true);
            if (value != null)
            {

                     if (this.SwitchThemeCommand.CanExecute(value))
                        this.SwitchThemeCommand.Execute(value); 
            }
        }
    }