2012-07-31 80 views
0

有沒有什麼辦法以編程方式解析綁定表達式?我有一個模板化的控件,它有很多複雜的內部工作,我不想公開。它接受一個列表,並公開一個完整項目視圖的模板,以及一些修改單個項目模板的細節。我想在我的控制,結合路徑有三個屬性,這樣我就可以如下暴露模板:Silverlight - 以編程方式解決綁定表達式

<src:MyControl x:Name="MyControl" 
       FullViewTemplate="{StaticResource FullViewTemplate}" 
       TopValueBinding="Items[2]" 
       BottomValueBinding="Items[6]" 
       CategoryBinding="Items[5]"/> 

裏面,我想取整的datacontext並將其提供給值轉換器,其將解決我的可配置綁定路徑。事情是這樣的:

PropertyPath path = new PropertyPath("Items[0]"); 
var value = Convert.ToDecimal(path.Resolve(dataSource)); 

我目前使用的屬性名和反射來提取值,但這不具備的靈活性,複雜的數據類型的工作,我不希望有寫一個巨大的塊的解析和反射邏輯來檢索字段值。

編輯:或者,能夠做這樣的事將是巨大的:

{Binding Path={TemplateBinding BottomValueMember}, Converter={StaticResource ScaleValueConverter}} 

但這似乎並沒有工作。有什麼想法嗎?

回答

0

所以 - 以後多挖我解決了這個用下面的代碼:

public class BindingEvaluator : DependencyObject 
{ 
    private static readonly DependencyProperty TargetProperty = 
     DependencyProperty.Register(
      "Target", 
      typeof(object), 
      typeof(BindingEvaluator), 
      new PropertyMetadata(null)); 

    private object Target 
    { 
     get { return GetValue(TargetProperty); } 
     set { SetValue(TargetProperty, value); } 
    } 

    private static BindingEvaluator _instance = new BindingEvaluator(); 
    private static BindingEvaluator Instance 
    { 
     get { return _instance; } 
    } 

    public static object Eval(Object instance, string path) 
    { 
     Binding binding = new Binding(path) { Source = instance }; 

     BindingOperations.SetBinding(Instance, TargetProperty, binding); 

     return Instance.Target; 
    } 
} 

信貸從這個職位的答案:Is there a way to get a property value of an object using PropertyPath class?

現在我只是通過整個數據項,並有轉換器搞定此事。