ListView鼠标悬停与MVVM

本文关键字:MVVM 悬停 鼠标 ListView | 更新日期: 2023-09-27 18:08:53

使用MVVM模式获取用户悬停在上面的项目最简单的方法是什么?

我看到ListView上有很多关于鼠标输入的事件,但是我找不到一个可绑定的属性。

ListView鼠标悬停与MVVM

这可以通过做几件事来完成。您将把列表框封装在它自己的UserControl中。在这个用户控件后面的代码中,您需要声明一个iccommand类型的依赖属性。在xaml中,您需要设置一个ListBoxItem样式,该样式处理了MouseEnterEvent。

<Grid>
    <Grid.Resources>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="MouseEnter"
                         Handler="HandleEnter" />
        </Style>
    </Grid.Resources>
    <ListBox ItemsSource="{Binding Items}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding Name}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

在后面的代码中,您将启动作为dependdecyproperty的iccommand。

public static readonly DependencyProperty SendToViewModelProperty =
        DependencyProperty.Register("SendToViewModel", typeof(ICommand), typeof(control), new PropertyMetadata(null));
    private void HandleEnter(object sender, MouseEventArgs e)
    {
        if (SendToViewModel != null)
        {
            var fe = sender as FrameworkElement;
            if (fe != null)
            {
                if (SendToViewModel.CanExecute(fe.DataContext))
                {
                    SendToViewModel.Execute(fe.DataContext);
                }
            }
        }
    }

这将触发iccommand属性,您应该在视图模型中设置该属性,该属性传递给ListBoxItem的数据上下文。