2012-08-16 24 views
0

我有一個有幾個屬性的對象。其中兩個用於控制目標文本框的寬度和高度。這裏有一個簡單的例子...WPF DataBinding從對象中恢復路徑的位置?

<DataTemplate DataType="{x:Type proj:SourceObject}"> 
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}"/> 
</DataTemplate> 

我也想綁定文本框的Text屬性。綁定的實際屬性不是固定的,而是在SourceObject的字段中命名的。所以最好我想做到這一點...

<DataTemplate DataType="{x:Type proj:SourceObject}"> 
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}" 
      Text="{Binding Path={Binding ObjPath}"/> 
</DataTemplate> 

這裏ObjPath是返回,這將是非常有效的結合路徑的字符串。但是這不起作用,因爲你不能對Binding.Path使用綁定。任何想法如何我可以實現同樣的事情?

對於更多的上下文,我會指出SourceObject是用戶可定製的,因此ObjPath可以隨時間更新,因此我不能簡單地在數據模板中放置一個固定路徑。

+0

你能移動ObjPath有價值的資源?然後你可以寫Text =「{Binding Path = {DynamicResource ObjPath}」 – dvvrd 2012-08-16 07:08:45

回答

1

您可以實施IMultiValueConverter並將其作爲BindingConverter用於您的文本屬性。但是你有這個問題,Textbox的值只有在你的ObjPath屬性改變(路徑本身)時纔會更新,而不是路徑指向的值。如果是這樣,那麼您可以使用BindingConverter,它使用反射返回綁定路徑的值。

class BindingPathToValue : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value[0] is string && value[1] != null) 
     { 
      // value[0] is the path 
        // value[1] is SourceObject 
      // you can use reflection to get the value and return it 
      return value[1].GetType().GetProperty(value.ToString()).GetValue(value[1], null).ToString(); 
     } 
     return null; 
    } 

    public object[] ConvertBack(object value, Type[], object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

在有你的資源轉換器:

<proj:BindingPathToValue x:Key="BindingPathToValue" /> 

和XAML中使用它:

<DataTemplate DataType="{x:Type proj:SourceObject}"> 
    <TextBox Width="{Binding ObjWidth}" Height="{Binding ObjHeight}"> 
     <TextBox.Text> 
      <MultiBinding Mode="OneWay" Converter="{StaticResource BindingPathToValue}"> 
       <Binding Mode="OneWay" Path="ObjPath" /> 
       <Binding Mode="OneWay" Path="." /> 
      </MultiBinding> 
     </TextBox.Text> 
    </TextBox> 
</DataTemplate>