我有几个包含Classes的类,需要在WPF Forms中访问它们的属性。我试图绑定" ppl"的属性。控制。使用Path = ppl.wife显然是不正确的。 (显然我是WPF的新手)
public MainWindow()
{
InitializeComponent();
department = "Rock Truck Drivers";
emp = new employee();
emp.first = "Fred";
emp.last = "Flintsone";
emp.address = "Bedrock";
emp.ppl.kid = "Pebbles";
emp.ppl.wife = "Wilma";
DataContext = emp;
}
}
public class employee
{
public string first { get; set; }
public string last { get; set; }
public string address { get; set; }
public other ppl = new other();
}
public class other
{
public string kid { get; set; }
public string wife { get; set; }
}
XAML
<TextBox
Width="120"
Height="23"
Margin="222,119,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding first, Mode=TwoWay}"
TextWrapping="Wrap" />
<TextBox
Width="120"
Height="23"
Margin="222,155,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding Path=last, Mode=TwoWay}"
TextWrapping="Wrap" />
<TextBox
Name="TextWife"
Width="120"
Height="23"
Margin="222,196,0,0"
Text="{Binding XPath=ppl.wife, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
TextWrapping="Wrap" />
答案 0 :(得分:1)
这里有两个问题。首先,您的绑定使用XPath=ppl.wife
。它应该是Path=ppl.wife
。您也可以省略Path=
部分(就像您绑定到first
一样)。
第二个问题是WPF中的绑定通常不适用于字段(请参阅the Binding Source overview)。
公共语言运行时(CLR)对象
您可以绑定到任何公共语言运行时(CLR)对象的公共属性,子属性以及索引器。绑定引擎使用CLR反射来获取属性的值。或者,实现ICustomTypeDescriptor或具有已注册的TypeDescriptionProvider的对象也可以使用绑定引擎。
如果您将ppl
字段更改为属性,则绑定将起作用。
public class Employee
{
public string First { get; set; }
public string Last { get; set; }
public string Address { get; set; }
public Other Ppl { get; } = new Other(); // Ppl is now a property rather than a field
}
public class Other
{
public string Kid { get; set; }
public string Wife { get; set; }
}