2
votes

I am writing a WPF application and I have a slider bound to a textbox and vice versa.

My problem is that when changing the value of the text box, I have to click out of the text box before the value of the slider is updated.

I would like the slider value to change as the user types text into the textbox or when the user presses enter whilst in the text box.

Heres the code I have:

XAML:

<Slider Name="sldrConstructionCoreSupplierResin" Minimum="0" Maximum="10" Grid.Column="1" Grid.Row="1" IsSnapToTickEnabled="True"/>
    <TextBox Name="txtConstructionCoreSupplierResin" Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, Converter={StaticResource RoundingConverter}}" Grid.Column="2" Grid.Row="1"/>

Code Behind:

public class RoundingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                double dblValue = (double)value;
                return (int)dblValue;
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                int ret = int.Parse(value.ToString());
                return ret;
            }
            return 0;
        }
    } 
2

2 Answers

4
votes

By default, bindings are updated when the control loses focus. That's why you're only seeing the change when you click out of the TextBox. You can change this using the UpdateSourceTrigger property of Binding, like this:

<TextBox Text="{Binding Value,ElementName=mySlider,UpdateSourceTrigger=PropertyChanged}" />

Now the TextBox will update its source whenever the Text property changes, rather than when it loses focus.

1
votes

Set the UpdateSourceTrigger property of the Binding to PropertyChanged

<TextBox Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, UpdateSourceTrigger = "PropertyChanged" Converter={StaticResource RoundingConverter}}"/>

See more here