2010-12-15 73 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