1

我正在尝试将 SelectionChanged 交互触发器添加到 WPF 中的 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>

我想我在这里做错了什么。

4

3 回答 3

1

您应该只将 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>
于 2013-04-12T09:48:12.310 回答
1

您的代码工作正常。您只需要提供一个合适的视图模型,例如

注意:使用 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
于 2013-04-12T10:00:18.257 回答
0
    // 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); 
            }
        }
    }
于 2014-05-12T16:32:34.473 回答