Search code examples
wpftextbox

WPF: pass my TextBox into my converter with my Property together


So i have this Converter:

public class ComboboxSelectedIndexToTextBoxBackgroundColor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int selectedIndex = (int)value;
        if (selectedIndex == 0)
            return "Red";
        else
            return "Green";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

My binding object has this Property (implement INotifyPropertyChanged):

public int ComboboxSelectedIndex
{
    get { return _comboboxSelectedIndex; }
    set
    {
        _comboboxSelectedIndex = value;
        OnPropertyChanged();
    }
}

My TextBox:

<TextBox Controls:TextBoxHelper.ClearTextButton="False"
         Background="{Binding ComboboxSelectedIndex, Converter={StaticResource ComboboxSelectedIndexToTextBoxBackgroundColor}}"
         Margin="0,0,0,0">

So if i want to use MultiBindingConverter and along my ComboboxSelectedIndex property i want slao to sent my TextBox - is it possible ? How can i do that ?


Solution

  • add Name="txt" attribute to TextBox and use ElementName in binding. TextBox will become the source of binding and without property Path it will be send to converter itself, not property value.

    <MultiBinding Converter="{StaticResource MvCvt}" Mode="OneWay">
        <Binding Path="ComboboxSelectedIndex"/>
        <Binding ElementName="txt"/>
    </MultiBinding>
    

    element can also send itself to binding using {RelativeSource Self}

    <MultiBinding Converter="{StaticResource MvCvt}" Mode="OneWay">
        <Binding Path="ComboboxSelectedIndex"/>
        <Binding RelativeSource="{RelativeSource Self}"/>
    </MultiBinding>
    

    "McCvt" is a some IMultiValueConverter implementation here