Reputation: 14274
I am trying to add a SelectionChanged interaction trigger to a ListBox in WPF so i can route the event to a command, but for some reason it's not working.
Here is my code
<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>
I guess i am doing something wrong here.
Upvotes: 1
Views: 2161
Reputation: 590
// 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);
}
}
}
Upvotes: 0
Reputation: 31192
You should just bind the SelectedIndex to a property in your DataContext, which leads to simplier code :
<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>
Upvotes: 1
Reputation: 43011
Your code works fine. All you need is to provide a suitable view model, e.g.
Note: using MVVM Light
public class TestViewModel : ObservableObject
{
public TestViewModel()
{
this.MyCommand = new RelayCommand<int>(i => Debug.WriteLine(i));
}
public RelayCommand<int> MyCommand { get; private set; }
}
Your Xaml with hard coded view model
<Window.DataContext>
<my:TestViewModel/>
</Window.DataContext>
<Border Background="Transparent">
<ListBox Name="MyListBox"
... etc
Upvotes: 1