将按钮对象从xaml发送到类(使用MVVM模型)

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

我想更改该代码以与 MVVM 兼容。

下面的代码带有代码隐藏

<Button
    x:Name="sevenBtn"
    Grid.Row="2"
    Grid.Column="0"
    Click="NumberBtn_Click"
    Content="7"
    Style="{StaticResource numberButtonsStyle}" />
private void NumberBtn_Click(object sender, RoutedEventArgs e)
{
    int selectedValue = int.Parse((sender as Button).Content.ToString());
}

我使用 CommunityToolkit.Mvvm、Microsoft.Xaml.Behavior.Wpf 有人可以帮助我吗? 谢谢

在 MVVM 中发送对象。

c# wpf xaml mvvm community-toolkit-mvvm
1个回答
0
投票

这是一个简单的示例代码:

  • 左侧:如何实现数字按钮。
  • 右侧:如何使用CommunityToolkit.Mvvm的另一个示例代码。

MainWindowViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace WpfAppTests;

public partial class MainWindowViewModel : ObservableObject
{
    [RelayCommand]
    private void UpdateNumber(string numberString)
    {
        if (int.TryParse(numberString, out int number) is true)
        {
            Number = number;
        }
    }

    [ObservableProperty]
    private int number;

    [ObservableProperty]
    private string someText = string.Empty;

    [RelayCommand]
    private void UpdateText(string text)
    {
        SomeText = text;
    }
}

MainWindow.xaml

<Window
    x:Class="WpfAppTests.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfAppTests"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <!--  Your number button sample code. -->
        <StackPanel Grid.Column="0">
            <Button
                Command="{Binding UpdateNumberCommand}"
                CommandParameter="{Binding Content, RelativeSource={RelativeSource Self}}"
                Content="5" />
            <TextBlock Text="{Binding Number}" />
        </StackPanel>
        <!--  Simple sample code of how to use the CommunitToolkit.Mvvm.  -->
        <StackPanel Grid.Column="1">
            <TextBox x:Name="InputTextBox" />
            <Button
                Command="{Binding UpdateTextCommand}"
                CommandParameter="{Binding ElementName=InputTextBox, Path=Text}"
                Content="Update text" />
            <TextBlock Text="{Binding SomeText}" />
        </StackPanel>
    </Grid>
</Window>
© www.soinside.com 2019 - 2024. All rights reserved.