簡體   English   中英

WPF我應如何評估屬性路徑?

[英]WPF How should I evaluate a property path?

我正在編寫一個自定義控件,並且有一個屬性路徑為字符串(請考慮comboBox.SelectedValuePath )。
在代碼中為任意對象求值該字符串的最佳方法是什么?

我顯然可以自己解析它,但這是一個hack,我希望該路徑支持comboBox.SelectedValuePath所做的一切(為了保持一致性)。

結果(感謝Aran Mulholland):

對此性能不確定,但是我現在不太在意性能。

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

創建一個對象,該對象具有一個類型為object的依賴項屬性,將其綁定設置為您的屬性路徑作為路徑,並將任意對象作為源。 綁定將執行,您可以看到屬性路徑末尾的內容(如果有)。 這是我發現在代碼中執行這種操作的唯一方法。 您可以編寫一個可以遵循屬性路徑的遞歸反射引擎,但是它已經完成了,我們在綁定時會使用它。 花五分鍾寫:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM