簡體   English   中英

DataType的DataTemplate - 如何在特定的ListBox中覆蓋此DataTemplate?

[英]DataTemplate for a DataType - how to override this DataTemplate in a particular ListBox?

我為我的寵物項目中的一些DataTypes創建了幾個DataTemplates。 這些數據模板非常酷,因為它們像魔術一樣工作,無論何時何地在UI中顯示,都可以神奇地轉換數據類型實例的外觀。 現在我希望能夠在一個特定的ListBox中更改這些DataType的DataTemplate。 這是否意味着我必須停止依賴WPF自動將數據模板應用於數據類型並將ax:Key指定給DataTemplates,然后使用該鍵在UI中應用Template / ItemTemplate?

ListBox包含各種數據類型的項目(所有數據類型都來自公共基類),現在它們都可以在不指定TemplateSelector的情況下神奇地工作,因為正確的模板是由listBox中項目的實際數據類型選擇的。 如果我使用x:Key來應用DataTemplates,那么我是否需要編寫TemplateSelector?

我是新手,只是試驗DataTemplates。 我想,哇,有多酷! 然后我想在不同的列表框和ooops中為相同的數據類型使用不同的數據模板,我不能這樣做:-)請幫助嗎?

您可以專門為ListBox指定ItemTemplate

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- your template here -->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

或者,如果您已經在某個ResourceDictionary定義了DataTemplate

<DataTemplate x:Key="MyTemplate">
      <!-- your template here -->
</DataTemplate>

然后你可以使用以下方法在ListBox上引用它:

<ListBox ItemTemplate="{StaticResource MyTemplate}" />

您無需為這些方法中的任何一種編寫模板選擇器


響應評論的示例

下面的示例演示了為窗口定義數據類型(在本例中為String )的默認DataTemplate ,然后在列表框中覆蓋它:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
            <Rectangle Height="10" Width="10" Margin="3" Fill="Red" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Rectangle Height="10" Width="10" Margin="3" Fill="Blue" />
                </DataTemplate>
            </ListBox.ItemTemplate>

            <sys:String>One</sys:String>
            <sys:String>Two</sys:String>
            <sys:String>Three</sys:String>
        </ListBox>
    </Grid>
</Window>

這會產生以下UI:

示例顯示

暫無
暫無

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

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