mvvm 事件绑定

Xaml:
<!-- MainWindow.xaml -->
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp">
    <Grid>
        <DataGrid ItemsSource="{Binding Students}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Action" 
                                    Command="{Binding DataContext.MyCommand, 
                                              RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                    CommandParameter="{Binding}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

cs:

// MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}

// Student.cs
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// RelayCommand.cs
public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
    public void Execute(object parameter) => _execute(parameter);

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}

// MainViewModel.cs
public class MainViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Student> Students { get; } = new()
    {
        new Student { Name = "Alice", Age = 20 },
        new Student { Name = "Bob", Age = 22 }
    };

    public RelayCommand MyCommand { get; }

    public MainViewModel()
    {
        MyCommand = new RelayCommand(ExecuteCommand);
    }

    private void ExecuteCommand(object param)
    {
        if (param is Student student)
        {
            MessageBox.Show($"操作学生: {student.Name}, 年龄: {student.Age}");
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

 

posted on 2025-03-24 12:27  空明流光  阅读(14)  评论(0)    收藏  举报

导航