将Slider值绑定到Textbox

时间:2014-07-24 09:28:08

标签: c# xml wpf

我想动态创建一个Slider,其值绑定到DockPanel内的TextBox。当我尝试这样做时,我无法将滑块值绑定到TextBox,并且在TextBox内部我收到以下消息: {Binding ElementName = slValue,Path = Value,UpdateSourceTrigger = PropertyChanged} 而不是Slider的值。

这是我到目前为止编写的代码:

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);

这是我正在尝试动态重新创建的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>

2 个答案:

答案 0 :(得分:3)

它应该以这种方式工作:

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

或更短:

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

甚至更短:

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

答案 1 :(得分:0)

这是一个如何在代码后面设置绑定的片段。我希望这能让你开始:

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

备注:使用ElementName要求名称是唯一的

编辑:你的评论的Binding-constructor(&#34; ValueChanged&#34;)中的路径看起来有点奇怪。你有没有试过&#34;价值&#34;代替?而Source-Property应该是控制权。