[英]Binding Slider value to Textbox
I'd like to dynamically create a Slider with its value bind to TextBox inside the DockPanel. 我想动态地创建一个Slider,将其值绑定到DockPanel中的TextBox。 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.
当我尝试这样做时,我无法将滑块值绑定到TextBox,并且在TextBox内收到以下消息: {Binding ElementName = slValue,Path = Value,UpdateSourceTrigger = PropertyChanged}而不是Slider的值。
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: 这是我要动态重新创建的xml代码:
<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>
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 });
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 备注:使用ElementName要求名称唯一
Edit: Your path in the Binding-constructor ("ValueChanged") of your comment looks a bit strange. 编辑:您的注释的绑定构造函数(“ ValueChanged”)中的路径看起来有点奇怪。 Have you tried "Value" instead?
您是否尝试过“值”? And the Source-Property should be the control.
并且源属性应该是控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.