问题描述
可以在code(即C#)创建的对象可用于在XAML约束力?
Can an object created in the code (ie C#) be used for binding in the XAML?
例如:
public class MyForm
{
private MyComplexObject complexObject;
public MyForm()
{
InitializeComponent();
}
public OnButtonClick(object sender, RoutedEventArgs e)
{
complexObject = new MyComplexObject();
}
}
直到一个按钮被点击未创建
complexObject
。但是,一旦该按钮被点击我想有一个绑定到 complexObject.ID
文本框开始显示的ID。
complexObject
is not created till a button is clicked. But once that button is clicked I would like to have a text box that is bound to complexObject.ID
start showing the Id.
我想这样做,在XAML,如果这是可能的。
I would like to do that in the XAML if that is possible.
可以这样做?如果是这样,怎么样?
Can this be done? If so, how?
推荐答案
一种可能是让你的XAML绑定到一个属性上的code后面。该属性的吸气将返回complexObject.ID,如果complexObject!= NULL。否则,它返回的东西默认,不管是空或0或默认值(的ID类型的)。同样,对于属性的setter将指定的值应用于complexObject.ID如果complexObject是,同样,不为null。
One possibility would be to have your XAML bind to a property on your code behind. The getter for that property would return complexObject.ID, if complexObject != null. Otherwise, it returns something "default", whether that's null or 0 or default(ID's type). Similarly, the setter for that property would assign value to complexObject.ID if complexObject is, again, not null.
public int ID
{
get
{
if (complexObject != null)
return complexObject.ID;
return 0; // or null or some appropriate default
}
set
{
if (complexObject != null)
complexObject.ID = value;
}
}
这篇关于WPF - 绑定在XAML于code创建后面的物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!