将滑块值绑定到文本框

本文关键字:文本 绑定 | 更新日期: 2023-09-27 18:14:38

我想动态地创建一个滑块,它的值绑定到DockPanel中的TextBox。当我试图这样做时,我不能将滑块值绑定到TextBox,并且在TextBox内,我得到以下消息:{Binding ElementName=slValue, Path= value, UpdateSourceTrigger=PropertyChanged}而不是滑块的值。

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

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>

将滑块值绑定到文本框

应该是这样的:

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

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

var b = new Binding();
b.Source = slValue;
b.Path = new PropertyPath("Value");
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
slValueTB.SetBinding(TextBox.TextProperty, b);
注意:使用ElementName需要名称是唯一的

编辑:你的评论的绑定构造器("ValueChanged")的路径看起来有点奇怪。你试过"价值"吗?Source-Property应该是控件