2012-01-18 45 views
0

我可能需要的东西一定的帮助,我不能在这一点搞清楚:如何获得GetBindingExpression目标反射

我需要(通过类不同RESX文件)来更新XAML的绑定在某具有特定名称前缀的控件的事件。作为对照有不同的类型,我也没有知道同一页面的外观somewhen在未来,我想做到这一点,只有反思...

var meth1 = control.GetType().GetMethod("GetBindingExpression"); 
var meth2 = control.GetType().GetMethod("SetBinding"); 
BindingExpression be = (BindingExpression)meth1.Invoke(target, null); 
Binding bind = be.ParentBinding; 
meth2.Invoke(target, new object[] { bind }); 

似乎是正确的想法给我,但我无法弄清楚如何从一个DependencyObject的目标的DependencyProperty之前不知道的DependencyObject类型...

我敢肯定,我缺少的东西,而容易在这里...

我知道我可以通过控件,只需将从ResourceManager对象获得的新字符串输入到文本属性的控制,但在这种情况下,我会再次检查文本,标题,任何属性......如果可能的话,反射似乎只是对我来说更干净的方式。

+0

为什么你不能将控件投射到FrameworkElement并直接使用方法而不是反射? – 2012-01-18 20:02:32

回答

0

您可以简单地使用下面的方法,

FrameworkElement fe = control as FrameworkElement; 
foreach(PropertyDescriptor pd in TypeDescriptor.GetProperties(control)) 
{ 
    FieldInfo field = control.GetType().GetField(pd.Name + "Property"); 
    if(field == null) 
     continue; 
    DependencyProperty dp = field.GetValue(control) as DependencyProperty; 
    if(dp == null) 
     continue; 
    BindingExpression be = control.GetBindingExpression(dp); 
    if(be == null) 
     continue; 

    // do your stuff here 

} 
+0

谢谢,这让我回到了正确的方向。由于silverlight不知道TypeDescriptor类,所以上述不起作用,但我按照下面的说明完成了。 – Seb 2012-01-19 09:59:59

0

由于关于投给FrameworkElement的两个提示,我设法回到正轨:在我认为会

foreach (var f in control.GetType().GetFields()) 
    { 
     DependencyProperty dp = f.GetValue(control) as DependencyProperty; 
     if (dp != null) 
     { 
      BindingExpression be = ((FrameworkElement)control).GetBindingExpression(dp); 
      if (be != null) 
      { 
       // stuff here 
      } 
     } 
    } 

从这里完成任务