开发者

ComboBox SelectedValue via Reflection as DependencyProperty

开发者 https://www.devze.com 2023-01-31 06:06 出处:网络
I need to get the Sel开发者_C百科ectedValue property of a Silverlight 4 ComboBox as a DependencyPproerty via Reflection but I am not sure how to do this.

I need to get the Sel开发者_C百科ectedValue property of a Silverlight 4 ComboBox as a DependencyPproerty via Reflection but I am not sure how to do this.

myComboBox.GetType().GetFields()

returns DependencyProperties but only four of the ComboBox's properties are returned and SelectedValue is not one of them.

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

gets the property but it's a System.Object and not a DependencyObject.

I am ultimately trying to get to the Bindings for the control, which requires a DependencyProperty not an Object.

Edit:

This is happening in a Behavior and I don't know what the control is, I am working with a ComboBox control right now. All I have is a string passed from XAML. In WPF I could use mySource="{x:Static ComboBox.SelectedValueProperty}" as the DependencyProperty but Silverlight doesn't have x:Static in XAML. So I am trying to convert mySource="SelectedValue" to a DependencyProperty.


Does this work for you?

myComboBox.GetValue(ComboBox.SelectedValueProperty);

--EDIT--

To get a DependencyProperty from any Control type, use following code:

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--

Following code works for me in a 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.


The property is actually titled SelectedValueProperty but if you are trying to get the bindings for the control try this...

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

精彩评论

暂无评论...
验证码 换一张
取 消