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

ccgok5k5  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(140)

我想更改代码以与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());
}

我使用社区工具包。Mvvm,微软。Xaml。行为。Wpf有人能帮助我吗?谢谢
发送MVVM中的对象。

ebdffaop

ebdffaop1#

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

*左侧:如何实现数字按钮。
*右侧:另一个如何使用CommunityToolkit.mvvm的示例代码。
主窗口视图模型.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;
    }
}

主窗口.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>

相关问题