2008-11-06 31 views
6

我不確定這是否可能,但我想我會問。首先,爲了我的目的,我需要這個工作在C#部分而不是XAML部分。這是我有,它的工作原理:綁定源是屬性路徑的字符串

public partial class MyClass1 : Window 
{ 
    public MyClass2 MyClass2Object { get; set; } 

    public MyClass1() 
    { 
      InitializeComponent(); 
      MyClass2Object = new MyClass2(); 
      Binding binding = new Binding(); 
      binding.Source = MyClass2Object; 
      binding.Path = new PropertyPath("StringVar"); 
      TextBoxFromXaml.SetBinding(TextBox.TextProperty, binding); 
    } 
} 
public class MyClass2 
{ 
    public string StringVar { get; set; } 

    public MyClass2() 
    { 
      StringVar = "My String Here"; 
    } 
} 

而這將綁定到我的StringVar屬性完全如何我喜歡它。然而,我的問題是如果我在設置綁定源時使用了字符串「MyClass2Object.StringVar」。我意識到我可以使用split函數從較長的字符串中分離出「MyClass2Object」和「StringVar」。然後我可以用分割的第二個結果替換新的PropertyPath行。但是,如何根據拆分的第一個結果來替換binding.Source行。如果這是可能的,我將能夠傳遞一個像「MyClass2Object.StringVar」這樣的字符串,並將TextBox的Text屬性綁定到該屬性,或者如果我傳遞一個像「AnotherClassObject.StringProperty」的字符串並將TextBox的Text屬性綁定到在名爲AnotherClassObject的變量中實例化的對象的StringProperty屬性。我希望我有道理。

+0

你想這樣做可能會略多於你所描述的更清楚一些「假」的代碼。 – 2008-11-06 04:14:00

回答

12

這聽起來像你想要PropertyPath是「Property.Property」,它將工作,但爲了綁定工作,它需要一個源對象的第一個屬性。我知道的兩個選項是DataContextSource

與樣品代碼的另一種方法是:

public partial class Window1 : Window 
{ 
    public MyClass2 MyClass2Object { get; set; } 
    public Window1() 
    { 
     // use data context instead of source 
     DataContext = this; 

     InitializeComponent(); 

     MyClass2Object = new MyClass2(); 
     Binding binding = new Binding(); 
     binding.Path = new PropertyPath("MyClass2Object.StringVar"); 
     TextBoxFromXaml.SetBinding(TextBox.TextProperty, binding); 
    } 
} 

public class MyClass2 
{ 
    public string StringVar { get; set; } 
    public MyClass2() 
    { 
     StringVar = "My String Here"; 
    } 
} 
+0

哦,謝謝你,那工作。我可以發誓我嘗試過。非常感謝。 – Nick 2008-11-06 04:34:42