2012-04-08 35 views
0

我有一個基類和另一個繼承自基類的類。 基類有一個DependencyProperty(比如 「MyDPProperty」):在窗口的構造DataBinding不適用於繼承DependencyProperty

public int MyDPProperty 
{ 
    get { return (int)GetValue(MyDPPropertyProperty); } 
    set { SetValue(MyDPPropertyProperty, value); } 
} 
public static readonly DependencyProperty MyDPPropertyProperty =DependencyProperty.Register("MyDPProperty", typeof(int), typeof(ownerclass), new UIPropertyMetadata(0)); 

我寫道:

SomeWpfWindow.DataContext = new ChildClass(); 

,在我窗口的XAML代碼我有:

<TextBox x:Name="txt" 
     Text="{Binding Path=MyDPProperty, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> 

現在,綁定不起作用,雖然當我將它綁定在代碼後面時,它的工作原理如下:

SomeWpfWindow.txt.SetBinding(TextBox.TextProperty 
         , new Binding("MyDPProperty") 
         { 
          Source = InstanceOfChildClass, 
          UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, 
          Mode = BindingMode.TwoWay 
         }); 
+0

你能後的DP屬性的定義是什麼? – 2012-04-08 11:10:28

+0

請勿在評論中發佈。 _編輯問題。 – 2012-04-08 11:16:43

+0

類似的問題在這裏:http://stackoverflow.com/questions/6071086/wpf-how-can-i-make-uielement-support-binding – 2012-04-08 11:26:33

回答

0

您正在綁定代碼背後的屬性。你可以給你的窗口名稱(例如NAME =「winName」),並在綁定定義的ElementName:

x:Name="txt" Text="{Binding ElementName=winName, Path=MyDPProperty, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> 

還有其他的方式,例如,你可以添加一個靜態資源。這個鏈接可以幫助:

http://blog.jayway.com/2011/05/17/bind-from-xaml-to-property-defined-in-code-behind/