WPF - 从 UserControl 访问 ViewModel 中的 EventHandler

问题描述 投票:0回答:1

我正在尝试从 MainViewModel 获取 DataGrid 的 SelectionChangedEventHandler 实现,但我不断收到错误,但如果我将 EventHandler 放在 MainWindow 内,它就可以正常工作。

Error

'HardwareTestView' does not contain a definition for 'DataGrid_SelectionChanged' and no accessible extension method 'DataGrid_SelectionChanged' accepting a first argument of type 'HardwareTestView' could be found (are you missing a using directive or an assembly reference?)

ViewModel

public class MainViewModel
{
    private readonly ObservableCollection<Test>? _hardwareTests;
    public IEnumerable<Test>? HardwareTests => _hardwareTests;

    ...

    public MainViewModel()
    {
        _hardwareTests = new ObservableCollection<Test>();

        foreach (var item in hardwareTestList)
        {
            _hardwareTests.Add(new Test(item, string.Empty, string.Empty, "n/a"));

        }
    }
    static void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show("TEST");
    }
}

View (UserControl)

<UserControl x:Class="TestInterface.Views.HardwareTestView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" 
             d:DesignHeight="400" d:DesignWidth="500">
    
    <Grid>
        
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <!-- Row 0 -->
            <RowDefinition Height="auto" /> <!-- Row 1 -->
            <RowDefinition Height="auto" /> <!-- Row 2 -->
        </Grid.RowDefinitions>

        <DataGrid ItemsSource="{Binding HardwareTests}" Grid.Row="1" SelectionChanged="DataGrid_SelectionChanged" AutoGenerateColumns="False">

            <DataGrid.Columns>
                <DataGridTextColumn Header="HardwareName" Binding="{Binding HardwareName}" />
                <DataGridTextColumn Header="TestType" Binding="{Binding TestType}" />
                <DataGridTextColumn Header="TestPath" Binding="{Binding TestPath}" />
                <DataGridTextColumn Header="Result" Binding="{Binding Result}" />
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</UserControl>
c# wpf
1个回答
0
投票

您的应用程序结构是

MVVM
设计模式的半心半意的实现。

每个视图模型都应该继承自实现

INotifyPropertyChanged
接口的公共基类。有许多用于此目的的库以及其他帮助器类,例如通过 Nuget 提供的
CommunityToolkit.Mvvm
。社区工具包包含代码生成器来简化 MVVM 的实现。

编码您的需求的常用方法是将

SelectedTest
属性(测试类型)添加到
MainViewModel
,然后您可以将其绑定到数据网格的
SelectedItem property
。所选项目更改时要采取的任何操作都可以添加到属性设置器中。这样的属性应该以调用
PropertyChanged
事件的方式创建 - 您不能只使用标准 C# 自动属性。所有 MVVM 库都将包含此功能。

有关更多详细信息以及我对 WPF / MVVM 的看法,请查看我的博客文章

© www.soinside.com 2019 - 2024. All rights reserved.