Set Multibing for text - get and set

374 views Asked by At

I would like to bind my TextBox.Text to two different sources.

I have 2 ViewModels, one is general ViewModel and one is more specific (which is inherit from its parent).

Both ViewModels has a property called "Hotkey".

I would like to bind my TextBox.Text so it will get the value from the general ViewModel and set it to the specific ViewModel.

I tried the following:

<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" Foreground="#000">
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource test}">
            <Binding Path="DataContext.Hotkey" RelativeSource="{RelativeSource AncestorType={x:Type MetroStyle:MetroWindow}}" Mode="OneWay" />
            <Binding Path="Hotkey" Mode="OneWayToSource"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

It does get the value from the general ViewModel, but it doesn't set its value to the specific one (which inherits from the parent)

1

There are 1 answers

0
King King On

I believe the problem may be in the Converter you used for MultiBinding, I've just tried a simple demo and looks like that Converter should be implemented like this:

public class TestConverter : IMultiValueConverter
{
    private bool justConvertedBack;
    object IMultiValueConverter.Convert(object[] values, Type targetType, 
                     object parameter, System.Globalization.CultureInfo culture)
    {
        if (justConvertedBack) {
            justConvertedBack = false;
            return Binding.DoNothing;
        }
        return values[0];
    }

    object[] IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, 
                     object parameter, System.Globalization.CultureInfo culture)
    {
        justConvertedBack = true;
        return new object[] {null, value};
    }
}

It happens that after the ConvertBack has been done, the Convert will be triggered and keep the Text of your TextBox unchanged (although you tried deleting/modifying it before). So we need some flag justConvertedBack here to prevent that from occurring.

Currently changing the source from the general ViewModel will change the TextBox's Text but does not update the source from the specific ViewModel. However if setting/typing some value for the TextBox's Text will update the source from the specific ViewModel but won't reflect that value back to the source from the general ViewModel. I hope that behavior is what you want.