[英]Binding source is string with path to property
我不確定這是否可能,但我想我會問。 首先,為了我的目的,我要求它在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屬性。 我希望我有意義。
聽起來你希望PropertyPath是“Property.Property”,它可以工作,但是為了使綁定工作,它需要第一個Property的源對象。 我所知道的兩個選項是DataContext或Source 。
使用示例代碼,另一種選擇是:
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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.