Search code examples
wpfdata-bindingmultibinding

Multibinding in WPF for Button


My application is having 5 text boxes and I want content of them in my ExecuteInsert function. right now my Button contains following binding.

<Button 
    Content="Add" 
    HorizontalAlignment="Left" 
    Margin="22,281,0,0" 
    VerticalAlignment="Top" 
    Width="75" 
    Command="{Binding Add}" 
    CommandParameter="{Binding ElementName=txtname}" 
    RenderTransformOrigin="1.023,0.765"/>

And my ExecuteInsert function is as follows. I just want to pass multiple command parameters means(multibinding) can anybody help??

private void ExecuteInsert(object obj)
{
   TextBox textbox = obj as TextBox;

   try
   {
      ExecuteConnect(obj);            
      oleDbCommand.CommandText = "INSERT INTO emp(FirstName)VALUES ('" + textbox.Text + "')";
      oleDbCommand.ExecuteNonQuery();
      MessageBox.Show("Data Saved");
   }
   catch (Exception ex)
   {
      MessageBox.Show("ERROR" + ex);
   }
}

Solution

  • You will have to create the Multivalueconveter for this:

    Xaml:

    converter:

    <local:MyConverter x:Key="myConverter" />
    

    Button:

            <Button>
                <Button.CommandParameter>
                    <MultiBinding Converter="{StaticResource myConverter}">
                        <Binding Path="" ElementName=""/>
                        <Binding Path=""/>
                        <Binding Path=""/>
                    </MultiBinding>
                 </Button.CommandParameter>
            </Button>
    

    C#

    public class MyConverter : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return values;
            }
    
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    you will get the object array in the command handler.

    Thanks