2010-12-15 70 views
0

我需要Silverlight 4组合框的SelectedValue属性作为DependencyPproerty通过反射,但我不知道如何做到这一点。ComboBox SelectedValue通过反射作为DependencyProperty

myComboBox.GetType().GetFields() 

回报DependencyProperties但只有四个组合框的属性返回和的SelectedValue是不是其中之一。

myComboBox.GetType().GetProperty("SelectedValue") 

获取属性,但它是一个System.Object而不是一个DependencyObject。

我最终试图去控制的绑定,这需要一个DependencyProperty不是一个对象。

编辑:

这是在行为发生的事情,我不知道控制是什么,我有一个ComboBox控件的工作现在。我所拥有的是从XAML传递的字符串。在WPF中,我可以使用mySource="{x:Static ComboBox.SelectedValueProperty}"作为DependencyProperty,但Silverlight在XAML中没有x:Static。所以我试图将mySource="SelectedValue"转换为DependencyProperty。

回答

2

这是否适合您?

myComboBox.GetValue(ComboBox.SelectedValueProperty); 

- 编辑 -

要想从任何Control类型,使用DependencyProperty下面的代码:

DependencyProperty property = control.GetType().GetField(propertyName + "Property", 
      BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(control) as DependencyProperty; 

BindingExpression bindingExpression = control.GetBindingExpression(property); 

// Use bindingExpression.ParentBinding 

--edit 2--

下面的代码工作的我在一个Silverlight 4 Application

Control control = new ComboBox(); 
String propertyName = "SelectedValue"; 

DependencyProperty property = control.GetType().GetField(propertyName + "Property", 
     BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetValue(control) as DependencyProperty; 

BindingExpression bindingExpression = control.GetBindingExpression(property); 
// bindingExpression will be null since we just created a `ComboBox`. It does not have any bindings yet. 
+0

其实这是在行为发生的事情,我不知道控制是什么,我现在正在使用ComboBox控件。我所拥有的是从XAML传递的字符串。在WPF中,我可以使用mySource =“{x:Static ComboBox.SelectedValueProperty}”作为DependencyProperty,但Silverlight在XAML中没有x:Static。所以我试图将mySource =“SelectedValue”转换为DependencyProperty。 – strattonn 2010-12-15 15:30:15

+0

看起来不错,唯一的问题是GetProperty(“SelectedValueProperty”)返回null,GetProperty(“SelectedValue”)返回的对象不是DependencyProperty。 (GetFields需要添加“属性”。) – strattonn 2010-12-15 15:56:53

+0

这是一个错误。代码更新为使用'GetField'代替。 – decyclone 2010-12-15 16:00:11

0

属性是实际标题为SelectedValueProperty,但如果你想获取该控件绑定试试这个...

BindingExpression expression = myComboBox.GetBindingExpression(ComboBox.SelectedValueProperty); 
+0

是的,组合框。SelectedValue是一个DP,这就是我想去的地方,但这是一个行为,所以用户通过一个字符串传递一个属性的名称(参见上面的编辑)。所以我需要将字符串转换为DP。 – strattonn 2010-12-15 16:00:16