Dot-Net

WPF:為列錶框綁定設置綁定屬性

  • August 16, 2011

我有一個列錶框,我將 ItemsSource 綁定到儲存在 set DataContext 對像中的集合。這使得列表使用 ToString() 函式顯示。

<ListBox ItemsSource="{Binding SomeCollection}"></ListBox>                    

現在我想顯示集合中對象的屬性。所以我想定義一個模板等來對綁定列表中的所有對象執行此操作。我嘗試了各種不同的方法,但都沒有成功。我想做這樣的事情:

<ListBox ItemsSource="{Binding SomeCollection}">
   <ListBox.Template>
       <ControlTemplate>                                
           <ListViewItem Content="{Binding ThePropertyOnElm}"></ListViewItem>
       </ControlTemplate>
   </ListBox.Template>
</ListBox>

任何人都可以幫我解決這個問題嗎?

您無需指定模板,只需使用 DisplayMemberPath 屬性,如下所示:

<ListBox ItemsSource="{Binding SomeCollection}" DisplayMemberPath="ThePropertyOnElm" />

希望這可以幫助!

我認為這是你想要做的:

<ListBox ItemsSource="{Binding SomeCollection}">
   <ListBox.ItemTemplate>
       <DataTemplate DataType="{x:Type local:YourDataType}">                                
           <TextBlock Text="{Binding ThePropertyOnElm}" />
       </ControlTemplate>
   </ListBox.ItemTemplate>
</ListBox>

ListBox 的模板將修改實際列錶框的外觀,而 itemtemplate 將控制列錶框中各個項目的外觀。我將 controltemplate 更改為 DataTemplate 並將其分配給 YourDataType 的類型。此外,我在數據模板中使用了一個文本塊而不是 listboxitem,因為數據模板被分配給 listboxitem(它應該包含某種類型的內容而不是另一個 listboxitem)。

我沒有嘗試編譯這個,所以它可能不完全正確。如果它沒有讓我知道並且我會採取額外的步驟!

引用自:https://stackoverflow.com/questions/1432591