代码隐藏:检查控件的 属性 是否已绑定
Code Behind: Check if property of a control is bound
如果控件的 属性 已绑定并且似乎无法找到正确的方法,我正在寻找一种方法来检查后面的代码。我想我需要先获取 FieldInfo(在通用方法中使用 System.Windows.Controls.Control 控件):
FieldInfo te = null;
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(control))
{
if (prop.Name.Equals("Visibility"))
{
te = control.GetType().GetField(prop.Name + "Property");
break;
}
}
...找到 PropertyDescriptor,但找不到 FieldInfo。
FieldInfo gg = control.GetType().GetField("Visibility", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg1 = control.GetType().GetField("VisibilityProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg2 = typeof(Control).GetField("Visibility", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg3 = typeof(Control).GetField("VisibilityProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
...所有 return null 作为 FieldInfo。找到 FieldInfo 后,我想检查该值是否已通过以下方式绑定:
DependencyProperty dp = (DependencyProperty)field.GetValue(control);
if (control.GetBindingExpression(dp) == null) ...
有什么想法吗?
您可以尝试使用BindingOperations.GetBinding
获取绑定对象。喜欢,
// textBox3 is an instance of a TextBox
// the TextProperty is the data-bound dependency property
Binding myBinding = BindingOperations.GetBinding(textBox3, TextBox.TextProperty);
参考。 How to: Get the Binding Object from a Bound Target Property
如果控件的 属性 已绑定并且似乎无法找到正确的方法,我正在寻找一种方法来检查后面的代码。我想我需要先获取 FieldInfo(在通用方法中使用 System.Windows.Controls.Control 控件):
FieldInfo te = null;
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(control))
{
if (prop.Name.Equals("Visibility"))
{
te = control.GetType().GetField(prop.Name + "Property");
break;
}
}
...找到 PropertyDescriptor,但找不到 FieldInfo。
FieldInfo gg = control.GetType().GetField("Visibility", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg1 = control.GetType().GetField("VisibilityProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg2 = typeof(Control).GetField("Visibility", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo gg3 = typeof(Control).GetField("VisibilityProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
...所有 return null 作为 FieldInfo。找到 FieldInfo 后,我想检查该值是否已通过以下方式绑定:
DependencyProperty dp = (DependencyProperty)field.GetValue(control);
if (control.GetBindingExpression(dp) == null) ...
有什么想法吗?
您可以尝试使用BindingOperations.GetBinding
获取绑定对象。喜欢,
// textBox3 is an instance of a TextBox
// the TextProperty is the data-bound dependency property
Binding myBinding = BindingOperations.GetBinding(textBox3, TextBox.TextProperty);
参考。 How to: Get the Binding Object from a Bound Target Property