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

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

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

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

而且我想从我的2 Text中将2 TexBox属性传递给此命令。

如果我只想传递1个Text属性,则使用此command

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

[没有Converter的机会吗?

wpf button command bind
2个回答
0
投票

您可以尝试执行以下操作。首先,通过实现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>

0
投票

最简单的方法是将两个文本框的Text属性绑定到视图模型中的字符串,并在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; }
© www.soinside.com 2019 - 2024. All rights reserved.