我正在寫一個自定義控件,我有一個屬性路徑作爲字符串(想想comboBox.SelectedValuePath
)。
代碼中爲任意對象評估此字符串的最佳方式是什麼?WPF我應該如何評估屬性路徑?
我明顯可以自己解析它,但它是一個黑客,我想路徑支持一切comboBox.SelectedValuePath
(一致性)。
結果(感謝阿蘭穆赫蘭):
不知道關於這樣的表現,但我不爲業績在意現在。
public class BindingEvaluator {
#region Target Class
private class Target : DependencyObject {
public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
"Result", typeof(IEnumerable), typeof(BindingEvaluator)
);
public object Result {
get { return this.GetValue(ResultProperty); }
set { this.SetValue(ResultProperty, value); }
}
}
#endregion
public object GetValue(object source, string propertyPath) {
var target = new Target();
BindingOperations.SetBinding(target, Target.ResultProperty, new Binding(propertyPath) {
Source = source,
Mode = BindingMode.OneTime
});
return target.Result;
}
}
是否注意到當Result屬性是類型對象時,Target中DependencyProperty的聲明類型是IEnumerable? – dtm 2013-06-04 23:14:39
@dtm可能只是我的錯誤 - 發佈中間版本而不是最終版本。不過那是很久以前的事了,我不記得了。如果我找到這個代碼,我會糾正這個問題,否則如果你測試了它,請讓我知道你的發現。 – 2013-06-04 23:47:48
我沒有實現類似這樣的依賴項屬性和屬性本身匹配的類型;然而,令人驚訝的是,它仍然有效,如果我用DepedencyProperty.Register中的Object代替IEnumerable。不知道該怎麼做... – dtm 2013-06-05 19:58:17