Search code examples
wpfxamlicommand

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


So i have 2 TextBox and button with simple command:

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

And i want to pass to this command the 2 Text properties from my 2 TexBox.

In case i want to pass only 1 Text property i used this command:

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

Any chance to do that without Converter ?


Solution

  • You can try to create a converter for multiple values by implementing IMultiValueConverter interface:

    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 };
        }
    }
    

    Then use it in xaml. Declare the converter instance in Window or App resources

    <ResourceDictionary>                    
        <MultiTextConverter x:Key="multiTextConverter"/>
    </ResourceDictionary>
    

    And use in button CommandParameter binding

    <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>