Search code examples
c#wpfdata-bindingtextboxslider

How to WPF Slider and Textbox two way binding?


i want slider value to binding on textbox and textbox to slider value(user interaction). im now just textbox binded of slider value. How can i get it?

<TextBox 
Width="70" 
Height="20" 
Grid.Row="1" 
Margin="0 0 80 180" 
x:Name="AO1text"               
Text="{Binding ElementName=AOch1,Path=Value, StringFormat={}{0:F2}}"/>
<Slider 
x:Name="AOch1" 
Maximum="20" 
Minimum="4" 
Value="{Binding ao1value}" 
Width="250" 
BorderThickness="5" 
TickPlacement="BottomRight"

Solution

  • try this

    <TextBox Width="120" Text="{Binding ElementName=AOch1, Path=Value, StringFormat={}{0:N0}, UpdateSourceTrigger=PropertyChanged}"/>
    <Slider x:Name="AOch1" Maximum="100" Minimum="0" Width="250" />
    
    // Get value from Slider
    targetObject.Value = AOch1.Value;
    

    The recommended approach is:

    1. Create a class with property, like Value
    public class ItemModel 
    { 
        double _Value = 4;
    
        public double Value
        {
            get => _Value;
            set
            {
                if (value < 4)
                    value = 4;
    
                if (value > 20)
                    value = 20;
    
                if (_Value != value)
                {
                    _Value = value;
                    // Notify Property Changed
                }
            }
        }
    }
    
    // Window1.xaml.cs
    ItemModel model = new ItemModel();
    
    // Window1_Loaded
    yourGrid.DataContext = model;
    
    1. Bind ItemModel.Value to the TextBox.Text and Slider.Value.
    <TextBox Text="{Binding Path=Value, StringFormat={}{0:F2}, UpdateSourceTrigger=PropertyChanged}"/>
    <Slider Value="{Binding Path=Value}" Maximum="20" Minimum="4" Width="250" BorderThickness="5" TickPlacement="BottomRight" />
    
    1. In this way, in the code section, you only need to access ItemModel.Value.