WPF:如何将 2 个文本框的 2 个文本属性传递到我的按钮命令中

WPF: how to pass 2 text properties from 2 TextBoxes into my Button command

所以我有 2 个 TextBox 和带有简单命令的按钮:

    <Button ToolTip="Save" Command="{Binding SaveCommand}"/>   

我想将我的 2 TexBox.

中的 2 Text 属性传递给此命令

万一我只想传递 1 Text 属性 我用这个 command:

CommandParameter="{Binding Text, ElementName=yourTextBox}"

没有 Converter 有没有机会做到这一点?

您可以尝试通过实现 IMultiValueConverter 接口为多个值创建转换器:

public class MultiTextConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        //logic to aggregate two texts from object[] values into one object
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return new[] { Binding.DoNothing };
    }
}

然后在xaml中使用它。在 WindowApp 资源

中声明转换器实例
<ResourceDictionary>                    
    <MultiTextConverter x:Key="multiTextConverter"/>
</ResourceDictionary>

并在按钮CommandParameter绑定中使用

<Button ToolTip="Save" Command="{Binding SaveCommand}">
   <Button.CommandParameter>
       <MultiBinding Converter="{StaticResource multiTextConverter}">
           <Binding ElementName="yourTextBox1" Path="Text"/>
           <Binding ElementName="yourTextBox2" Path="Text"/>
       </MultiBinding>
   </Button.CommandParameter>
</Button>

最简单的方法是将两个文本框的文本 属性 绑定到视图模型中的字符串,然后在 ICommand 的 Execute() 方法中处理这些字符串。

查看:

<TextBox x:Name="firstTextBox" Text="{Binding FirstText}"/>
<TextBox x:Name="secondTextBox" Text="{Binding SecondText}"/>

查看模型:

public string FirstText { get; set; } //Also invoke PropertyChanged event if necessary
public string SecondText { get; set; }