将文本框绑定到按钮 (MVVM)

Binding TextBoxes to a Button (MVVM)

我正在制作一个应用程序来生成指定时间段(例如一周)的食谱。作为此应用程序的一部分,我必须列出成分。这些成分可以由用户指定,所以我做了一个 UserControl 来添加一个成分。此 UserControl 包含 6 个 TextBox-es 和一个 Button。我想要做的是当用户点击按钮时,用户指定的成分(以及文本框)将被添加到成分列表中。

我正在使用 MVVM 架构和 MultiValueConverter 将文本框绑定到按钮。我注意到 Convert 方法仅在实例化时被调用,但在我单击 Button 时没有被调用。

如何在使用 MVVM 的情况下解决这个问题?

感谢您的建议和时间!

对应的代码片段:

AddIngredientView.xaml:

<UserControl.Resources>
        <ResourceDictionary>
            <converters:IngredientConverter x:Key="IngredientConverter"/>
        </ResourceDictionary>
</UserControl.Resources>
    
<StackPanel>
    <TextBlock Text="Étel hozzáadása" Foreground="White" FontSize="28" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,0,0,20"/>

    <TextBox Name="nameTextBox"         ToolTip="Név"            Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>
    <TextBox Name="weightTextBox"       ToolTip="Tömeg (g)"      Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>
    <TextBox Name="energyTextBox"       ToolTip="Energia (kcal)" Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>
    <TextBox Name="carbohydrateTextBox" ToolTip="Szénhidrát (g)" Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>
    <TextBox Name="proteinTextBox"      ToolTip="Fehérje (g)"    Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>
    <TextBox Name="fatTextBox"          ToolTip="Zsír (g)"       Width="250" Height="40" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="5" Style="{StaticResource ModernTextbox}"/>

    <Button Content="További értékek" Foreground="#353340" FontSize="14" Margin="0,10,60,0">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="TextElement.FontFamily" Value="Fonts/#Poppins"/>
                <Setter Property="Background"             Value="DarkGray"/>
                <Setter Property="Cursor"                 Value="Hand"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#353340"/>
                        <Setter Property="Foreground" Value="DarkGray"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Border Width="130" Height="25" CornerRadius="12" Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>
    <Button Content="Hozzáadás" Foreground="#353340" FontSize="14" Margin="500,50,0,0" Command="{Binding AddIngredientCommand}">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="TextElement.FontFamily" Value="Fonts/#Poppins"/>
                <Setter Property="Background" Value="DarkGray"/>
                <Setter Property="Cursor" Value="Hand"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#353340"/>
                        <Setter Property="Foreground" Value="DarkGray"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Border Width="100" Height="25" CornerRadius="12" Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Button.Template>
        <Button.CommandParameter>
            <MultiBinding Converter="{StaticResource IngredientConverter}" UpdateSourceTrigger="PropertyChanged">
                <Binding Path="Text" ElementName="nameTextBox"/>
                <Binding Path="Text" ElementName="weightTextBox"/>
                <Binding Path="Text" ElementName="energyTextBox"/>
                <Binding Path="Text" ElementName="carbohydrateTextBox"/>
                <Binding Path="Text" ElementName="proteinTextBox"/>
                <Binding Path="Text" ElementName="fatTextBox"/>
            </MultiBinding>
        </Button.CommandParameter>
    </Button>
</StackPanel>

IngredientConverter.cs:

public class IngredientConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Concat(values[0], ",", values[1], ",", values[2], ",", values[3], ",", values[4], ",", values[5]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return (value as string).Split(',');
    }
}

AddIngredientViewModel.cs:

public class AddIngredientViewModel : ViewModelBase
{
    #region Fields

    private YazioRecipesAddOnModel _model;

    #endregion

    #region Properties

    public DelegateCommand AddIngredientCommand { get; private set; }

    #endregion

    #region Constructor

    public AddIngredientViewModel(YazioRecipesAddOnModel model)
    {
        _model = model;
        AddIngredientCommand = new DelegateCommand(param => AddIngredient(param.ToString()));
    }

    #endregion

    #region Public methods

    public void AddIngredient(String ingredientString)
    {
        if (ingredientString == null)
            return;

        _model.AddIngredient(ingredientString);
    }

    #endregion
}

您应该将每个 TextBox 绑定到视图模型的不同来源 属性,例如:

<TextBox Name="weightTextBox" Text="{Binding Weight}" />

然后您可以直接在 AddIngredient 方法中访问这些值:

string ingredientString = string.Concat(this.Weight, "," ...);
_model.AddIngredient(ingredientString);

MVVM 的一个关键方面是在视图模型中实现应用程序逻辑。不要为此使用转换器。