Microsoft.Xaml.Behaviors绑定ListView 事件

李辉
2023-12-01

.NET Core 6.0 开发WPF应用程序,使用Microsoft.Xaml.Behaviors事件绑定:

首先应用命名空间:

  xmlns:i="http://schemas.microsoft.com/xaml/behaviors"      

Xaml代码如下:

<ListView x:Name="lstView"  VerticalAlignment="Top"   ItemsSource="{Binding Categories}" DisplayMemberPath="CATEGORY_NAME" SelectedValuePath="CATEGORY_ID">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <i:InvokeCommandAction Command="{Binding SelectionChanged}" CommandParameter="{Binding ElementName=lstView, Path=SelectedItem}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
</ListView>

后端写法:

 public ICommand SelectionChanged { get; }
public ObservableCollection<DeviceCategory> Categories { get; set; } = new ObservableCollection<DeviceCategory>();

SelectionChanged = new DelegateCommand<DeviceCategory>(DeviceCategoryChanged); 
void DeviceCategoryChanged(DeviceCategory category)
{
    //DO SOMTHING
}

 注意如果方法签名同Xaml绑定的类型不一致,将导致事件无法触发

 类似资料: