ComboBox SelectedValue通过Reflection作为DependencyProperty

时间:2010-12-15 15:15:08

标签: silverlight combobox

我需要通过Reflection获取Silverlight 4 ComboBox的SelectedValue属性作为DependencyPproerty,但我不知道如何做到这一点。

myComboBox.GetType().GetFields()

返回DependencyProperties,但只返回四个ComboBox属性,而SelectedValue不是其中之一。

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

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

我最终试图进入控件的Bindings,这需要DependencyProperty而不是Object。

编辑:

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

2 个答案:

答案 0 :(得分:2)

这对你有用吗?

myComboBox.GetValue(ComboBox.SelectedValueProperty);

- 编辑 -

要从任何DependencyProperty类型获取Control,请使用以下代码:

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

- 编辑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.

答案 1 :(得分:0)

该属性实际上标题为SelectedValueProperty,但如果您尝试获取控件的绑定,请尝试此操作...

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