簡體   English   中英

簡單綁定的問題

[英]Problem with simple binding

我試圖僅使用XAML將集合綁定到ListBox。 這種方法行得通,但是只顯示MyProject.mainItem (這是對象類型),而不是實際值。

在分配為DataContext的類中,我有以下內容:

ItemCatalog.Add(new mainItem { Ref = "555555", ItemName = "First Item" });

在具有ListBox的頁面上的XAML中,我有以下內容:

<ListBox ItemsSource="{Binding ItemCatalog}">
       <DataTemplate>
             <StackPanel Margin="0,0,0,17" Width="432">
                  <TextBlock Text="{Binding Ref}" TextWrapping="Wrap"  Foreground="Black" />
                  <TextBlock Text="{Binding ItemName}" TextWrapping="Wrap" Margin="12,-6,12,0" Foreground="Black" />
             </StackPanel>
       </DataTemplate>
</ListBox>

它遍歷整個ItemCatalog集合,但是ItemCatalog顯示諸如First Item類的值,它只是顯示對象的類型。 謝謝

如果主要項目沒有可視化表示IE,則為數據模板。 然后它將調用該對象的ToString()進行顯示。 這就是為什么您看到對象類型的原因。

之所以無法使用數據模板,是因為您試圖像ListBoxItem一樣插入它。

您想要做的是覆蓋ItemTemplate

<ListBox ItemsSource="{Binding ItemCatalog}">
    <ListBox.ItemTemplate>
         <DataTemplate/>
    </ListBox.ItemTemplate>
</ListBox>

另外,您還要將DataTemplate中的DataType屬性設置為適當的類型。

希望能幫助到你。

代碼說DataTemplate是ListBox的項目之一。

嘗試在<DataTemplate>周圍添加<ListBox.ItemsTemplate>標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM