2012-11-25 122 views
1

假設我有一個ObservableCollection(類型爲MyRow)(稱爲行)行。在MyRow中,我有一些屬性,包括一個ObservableCollection(類型MyRowContents)(稱爲內容) - 基本上是該行中所有內容的列表。 MyRowContents也有幾個屬性,包括DisplayContents(字符串)。將複雜對象綁定到DataGrid

例如...對於具有2行和3列的DataGrid,數據結構將是2個「行」,並且每個都包含3個「內容」。

我在XAML的DataGrid中做了些什麼,使單元格內容顯示Rows [i] .Contents [j] .DisplayContents?

編輯:

嗨,對不起,在初始消息不夠清晰。我正在嘗試創建一個能夠動態顯示數據的數據網格(來自未知數據庫表)。

我用這個作爲指導:http://pjgcreations.blogspot.com.au/2012/09/wpf-mvvm-datagrid-column-collection.html - 我可以動態顯示列。

<DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="False" 
       w:DataGridExtension.Columns="{Binding ElementName=LayoutRoot, Path=DataContext.Columns}" /> 

我只是不知道如何動態顯示行數據。

MyRow是:

public class MyRow 
{ 
    public int UniqueKey { get; set; } 
    public ObservableCollection<MyRowContents> Contents { get; set; } 
} 

MyRowContents是:

public class MyRowContents 
{ 
    public string ColumnName { get; set; } // Do I need this? 
    public object DisplayContents { get; set; } // What I want displayed in the grid cell 
} 

我有我的觀點模型,你可以看到一個公共屬性的ObservableCollection行就是我在的ItemsSource綁定。但我不知道如何讓每個MyRowContents的「DisplayContents」顯示在網格視圖的相應單元格中。

鑑於我可以動態顯示列名稱,可以進行以下假設:內容(在MyRow中)的項目順序將匹配列的順序。

感謝

+0

我編輯了你的標題。請參見「[應的問題包括‘標籤’,在他們的頭銜?(http://meta.stackexchange.com/questions/19190/)」,這裏的共識是「不,他們不應該」。 –

+0

你可以發佈一些代碼,描述也很複雜,就像你的類結構? –

+0

是的,我已經更新了最初的消息。謝謝。 – theqs1000

回答

1

首先你必須把行ID在RowContent所以您的應用程序邏輯應該是類似的:

RowContent.cs:

public class RowContent 
{ 
    //public string ColumnName { get; set; } "you dont need this property." 

    public int ID; //You should put row ID here. 
    public object DisplayContents { get; set; } "What is this property type, is string or int or custom enum??" 
} 

RowViewModel.cs:

public class RowViewModel 
{ 
    public ObservableCollection<MyRowContents> Contents { get; set; } 
} 

現在你必須把你的集合在Window.DataContext中,以便能夠綁定我噸在數據網格

MainWindow.xaml.cs:

public partial class MainWindow : Window 
{ 
    private RowViewModel rvm = new RowViewModel(); //Here i have made new instance of RowViewModel, in your case you have to put your ViewModel instead of "new RowViewModel();"; 

    public MainWindow() 
    { 
     InitializeComponent(); 

     DataContext = rvm; // this is very important step. 
    } 
} 

最後一步是在窗口XAML。

MainWindow.xaml:

<DataGrid ItemsSource="{Binding Path=Contents}" AutoGenerateColumns="false"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Row ID" Binding="{Binding Path=ID,UpdateSourceTrigger=PropertyChanged}"/> 
     <DataGridTextColumn Header="your row header" Binding="{Binding Path=DisplayContents,UpdateSourceTrigger=PropertyChanged}"/> 
    </DataGrid.Columns> 
</DataGrid> 

有五種類型的DataGridColumn,你必須根據DisplayContents屬性的類型來選擇合適的類型。

+0

如果您想更改列標題或者您的類中有自定義類型(本例中爲MyClass),請告訴我解釋方式。祝你好運, – MoHaKa

+0

嗨,謝謝你的回覆。抱歉,我的初始信息不夠清晰,我已更新了最初的信息,並提供了更多詳細信息。 – theqs1000

+0

沒問題,我會回答你的 – MoHaKa