2013-03-08 64 views
2

我有一個StackPanel,它將GridColumns設置爲實體屬性/表列的列。許多列是來自其他表的外鍵。下面的一個簡短例子顯示了一次這樣的外鍵 - CustomerID。將外鍵表示爲WPF中的其他值GridViewColumn

<StackPanel Orientation="Vertical" Margin="5"> 
    <Label Content="Tests to Run" FontWeight="Bold" x:Name="TestsToRunLabel"/> 
    <ListView ItemsSource="{Binding SelectedTechnician.Tests}" 
     SelectedItem="{Binding SelectedTest}" x:Name="AvailableTestsListView" Height="140"> 
     <ListView.View> 
      <GridView> 
       <GridViewColumn Header="Id" Width="auto" DisplayMemberBinding="{Binding Id}"/> 
       <GridViewColumn Header="Test" Width="auto" DisplayMemberBinding="{Binding CustomerId}"/> 
      </GridView> 
     </ListView.View> 
    </ListView> 
</StackPanel> 

正如預期此簡單地示出了諸如客戶名稱或其他一些有用的值與該鍵而不是一些「用戶可讀的」值相關聯的整數值。

如果可能的話,我該如何「轉換」或表示像CustomerId這樣的外鍵以在Customer表中顯示其他值?

這實際上得到的關鍵,因爲它現在,並達到客戶表,並抓住像Customer.Name作爲其代表屬性在我的StackPanel。

注意事項:

測試和客戶的代碼優先實體。我也使用MVVM,所以如果這是我需要在ViewModel而不是XAML中操作的東西,請讓我知道。

+1

從你的代碼,好像你將你的「測試」列綁定到你的視圖模型上名爲「CustomerId」的屬性。如果你想綁定到「CustomerName」,你需要在你的視圖模型上定義這個屬性並手動處理這些數據。您可以在您的父視圖模型中包含一個Customer對象,並使用查詢根據您的CustomerId檢索所需的Customer對象。 – failedprogramming 2013-03-09 00:50:21

+0

@failedprogramming可以詳細說明「在我的父視圖模型中包含一個Customer對象」是什麼意思?作爲財產?將它實例化爲一個具體的對象?隨意發佈問題的答案。 – 2013-03-11 17:20:01

+0

在我的應用程序中,我使用單個窗口來顯示內容。我的各種屏幕分成UserControls和我有每個UserControl的WorkspaceViewModel類。如果我們以你的情況爲例,我可能會有一個顯示「Test」的UserControl。驅動該UserControl的TestWorkspaceViewModel類將擁有您的外鍵「CustomerId」。我將創建一個CustomerViewModel類,並將其作爲TestWorkspaceViewModel中的一個屬性包含在內。它將填充與您的答案中類似的代碼。 – failedprogramming 2013-03-11 22:29:26

回答

0

爲了解決我自己的問題,我創建了一套我的業務模型對象「只顯示」屬性,簡單地執行LINQ查詢返回一個更有意義的屬性/屬性/列:

public string CustomerName 
{ 
    get 
    { 
     var db = new Context(); 

     var customer = db.Customers.Find(CustomerId); 
     _customerName = customer.Name; 

     return _customerName; 
    } 
} 
+0

很高興看到你已經解決了你的問題。 – failedprogramming 2013-03-11 22:22:13

+0

@failedprogramming您的評論當然讓我思考在正確的方向。謝謝。 – 2013-03-11 22:23:52

+1

不用擔心。你可能已經知道的一件小事。將您的上下文包裝在using語句中以幫助處理它,並且在分配_customerName之前檢查該客戶是否爲空是非常有用的。 – failedprogramming 2013-03-11 22:32:42

相關問題