2012-04-22 88 views
0

比方說,我有一個域模型,如:綁定到派生屬性沒有代理對象在WPF MVVM

class User { 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string MiddleName { get; set; } 
    public int Age  { get; set; } 
    // tons of other stuff 
} 

我對這些所謂的UserListObservableCollection,我綁定到這樣一個DataGrid:

<dg:DataGrid ItemsSource="{Binding Path=UserList}" SelectedIndex="{Binding Path=Selecteduser}"> 
    <dg:DataGrid.Columns> 
     <dg:DataGridTextColumn Header="Name" Binding="{Binding Path=FirstName, Mode=OneWay}" /> 
     <dg:DataGridTextColumn Header="Age" Binding="{Binding Path=Age, Mode=OneWay}" /> 
    </dg:DataGrid.Columns> 
</dg:DataGrid> 

現在我決定爲用戶的全名添加一個網格列。我的User對象沒有此屬性,但如果您向我傳遞User對象,則該對象很容易計算。如何綁定到User對象上的派生「屬性」,而不需要爲User創建代理類(又名視圖模型),並重寫大量代碼以處理此代理,將域對象的狀態複製到代理對象等。 ?

一個相當乾淨明顯的解決方案將是一個擴展方法,但顯然你不能綁定到那個。

我只是想能夠告訴網格:這個專欄,給我一個用戶和一些關鍵指示這是什麼(例如「全名」),我會通過你回傳數據以使用爲列。

回答

4

你當然可以創建最多的派生屬性由多綁定像這樣的:

<DataGridTextColumn Header="FullName"> 
    <DataGridTextColumn.Binding> 
     <MultiBinding StringFormat="{}{0} {1}}"> 
      <Binding Path="FirstName"/> 
      <Binding Path="LastName"/> 
     </MultiBinding> 
    </DataGridTextColumn.Binding> 
</DataGridTextColumn> 

對於更復雜的東西,你可能需要直接綁定到用戶對象和使用binding converter與轉換器參數創建該導出的值:

public class UserConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     User user = (User)value; 
     string result = string.Empty; 

     switch ((string)parameter) 
     { 
      case "FullName": 
       result = string.Format("{0} {1}", user.FirstName, user.LastName); 
       break; 
     } 

     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

然後結合這樣的:

<DataGridTextColumn Header="FullName" 
    Binding="{Binding Converter={StaticResource UserConverter}, ConverterParameter=FullName}"/> 
+0

'MultiBinding StringFormat'非常適合我的示例,不適用於我的實際情況(這不僅僅是字符串格式),但這很好理解。但是,IValueConverter正是醫生所訂購的。 :) WPF程序員可能已經知道的東西,但我在一個陌生的代碼庫中混淆了。我覺得這樣的東西一定存在,但不知道它會是什麼樣子。我昨天的搜索引擎導致了我'IValueConverter',但我錯過了綁定字符串。謝謝。 :) – Mud 2012-04-22 21:59:35