2014-07-24 74 views
0

我想動態創建一個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> 
+1

'{綁定...}'是一個標記擴展只能在XAML中使用,而不能在代碼中使用。請參見[如何:在代碼中創建綁定](http://msdn.microsoft.com/zh-cn/library/ms742863.aspx)。 – Clemens

+0

我已經嘗試了與上例中相同的方式,但我仍然無法將其值綁定到TextBox。這是我迄今爲止設法做的:綁定myBinding =新的綁定(「ValueChanged」); myBinding.Source = slValue.Value; slValueTB.SetBinding(TextBox.TextProperty,myBinding); – user3154369

+1

如果你想編寫這樣的代碼,你正在做一些根本性的錯誤,即不使用[數據模板](http://msdn.microsoft.com/en-us/library/ms742521.aspx)。 –

回答

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

謝謝克萊門斯它工作:) – user3154369

0

這裏有一個片斷如何設置綁定後面的代碼。我希望這可以讓你開始:

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

備註:使用的ElementName需要名稱是唯一

編輯:您在您的評論的綁定構造函數(「的ValueChanged」)路徑看起來有點怪。你嘗試過「價值」嗎?來源 - 財產應該是控制。

+0

我試過你的答案。不幸的是,它不工作:/ – user3154369

+0

看到我的更新。但它指向克萊門斯同樣的東西稍後寫了 – Markus

+0

我試過了,但它仍然沒有工作:/。儘管謝謝你的幫助。 – user3154369