0
votes

I'd like to dynamically create a Slider with its value bind to TextBox inside the DockPanel. When I'm trying to do so I cannot bind the slider value to the TextBox, and inside the TextBox I'm getting the following message: {Binding ElementName=slValue, Path=Value, UpdateSourceTrigger=PropertyChanged} instead of the Slider's value.

Here's the code I've written so far:

double minimum = 0.0;
double maximum = 100.0;
double defaultValue = 5.0;
DockPanel item = new DockPanel();
item.VerticalAlignment = VerticalAlignment.Center;
Slider slValue = new Slider()
{
     Minimum = minimum,
     Maximum = maximum,
     TickFrequency = 1.0,
     Value = defaultValue,
     IsSnapToTickEnabled = true,
     Name = "slValue",
     Width = 100
};
TextBox slValueTB = new TextBox()
{
     Text = "{Binding ElementName=slValue, Path=Value, UpdateSourceTrigger=PropertyChanged}",
     TextAlignment = TextAlignment.Right,
     Width = 40,
};
item.Children.Add(slValue);
item.Children.Add(slValueTB);

And here's the xml code I'm trying to recreate dynamically:

        <DockPanel VerticalAlignment="Center" Margin="10">
            <TextBox Text="{Binding ElementName=slValue, Path=Value, UpdateSourceTrigger=PropertyChanged}" DockPanel.Dock="Right" TextAlignment="Right" Width="40" />
            <Slider Minimum="0" Maximum="100" TickPlacement="BottomRight" TickFrequency="5" IsSnapToTickEnabled="True" Name="slValue" />
        </DockPanel>
2
{Binding ...} is a markup extension that only works in XAML, not in code behind. See How to: Create a Binding in Code.Clemens
I've tried doing it the same way as in example above, but i still can't bind its value to the TextBox. Here's what I've managed to do so far: Binding myBinding = new Binding("ValueChanged"); myBinding.Source = slValue.Value; slValueTB.SetBinding(TextBox.TextProperty, myBinding);user3154369
If you want to write code like that you are doing something fundamentally wrong, namely not using data templates.H.B.

2 Answers

3
votes

It should work this way:

var b = new Binding();
b.Source = slValue;
b.Path = new PropertyPath("Value");
slValueTB.SetBinding(TextBox.TextProperty, b);

or shorter:

slValueTB.SetBinding(TextBox.TextProperty,
    new Binding
    {
        Source = slValue,
        Path = new PropertyPath("Value")
    });

or even shorter:

slValueTB.SetBinding(TextBox.TextProperty,
    new Binding("Value") { Source = slValue });
0
votes

Here's a snippet how to set a binding in code behind. I hope this gets you started:

var b = new Binding();
b.Source = slValue;
b.Path = new PropertyPath("Value");
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
slValueTB.SetBinding(TextBox.TextProperty, b);

Remark: Using ElementName requires that the name is unique

Edit: Your path in the Binding-constructor ("ValueChanged") of your comment looks a bit strange. Have you tried "Value" instead? And the Source-Property should be the control.