[英]WPF - Interaction Trigger not working in Listbox
我正在尝试将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>
我想我在这里做错了。
您应该只将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>
您的代码工作正常。 您所需要做的就是提供合适的视图模型,例如
注意:使用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
// 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.