【问题标题】:Why would you use DataTemplate in a ListView?为什么要在 ListView 中使用 DataTemplate?
【发布时间】:2015-03-05 19:12:15
【问题描述】:

有人可以向我解释一下如果我使用有什么区别吗 DataTemplate 在 XAML 中的 ListView 内?

我使用ListView 来显示我的ObservableCollection 中的内容,而没有使用DataTemplateDataTemplate 看起来完全一样?

那我为什么要使用数据模板?我想看一个简单的解释/例子。

【问题讨论】:

  • 您能否展示一段代码,您如何在 XAML 中使用 DataTemplate?您如何想象将带有文本的图像作为列表项?
  • 那么,不同之处在于,在数据模板中,我不仅可以放入文本,还可以放入任何内容,并从我的属性中决定它的外观?
  • 对。数据模板允许您做任何事情,而不仅仅是一个简单的文本块
  • 请查看互联网、博客、教程、MSDN 中的示例。例如,您可以放置​​一个 panel(例如 Grid)并将许多东西作为子项添加到此 panel

标签: c# wpf xaml windows-phone-8 windows-store-apps


【解决方案1】:

DataTemplate 用于以超越简单文本块的方式显示数据。确定这样做:

<ListView.ItemTemplate>
   <DataTemplate>
     <TextBlock Text="{Binding Name}"/>
   </DataTemplate>
</ListView.ItemTemplate>

不会给你买太多。但它允许你做这样的事情:

<ListView.ItemTemplate>
   <DataTemplate>
     <StackPanel>
        <Image Source="{Binding ImagePath}"/>
        <TextBlock Text="{Caption}"/>
     </StackPanel>
   </DataTemplate>
</ListView.ItemTemplate>

这很酷!您可以将 anything 放入模板中,因此它使ItemsControl(及其派生类)成为 WPF 中一些最强大的类。

【讨论】:

    【解决方案2】:

    请在此处查看#HighCore 的答案WPF MVVM Why use ContentControl + DataTemplate Views rather than straight XAML Window Views?

     <Window x:Class="MyViews.MainWindow"   
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
        xmlns:viewmodel="clr-namespace:Project.ViewModel" 
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="{Binding Title, Mode=TwoWay}"  Height="{Binding Height, Mode=TwoWay}" Width="{Binding Width, Mode=TwoWay}" Left="{Binding Left, Mode=TwoWay}" Top="{Binding Top, Mode=TwoWay}" WindowStartupLocation="CenterScreen">
    
    
    <Window.Resources>     
        <HierarchicalDataTemplate DataType="{x:Type viewmodel:OtherViewModel1}">            
            <ContentPresenter Content="{Binding Path=Text}" />
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type viewmodel:OtherViewModel2}">
            <view:ConnectivityLED />
        </DataTemplate>      
    </Window.Resources>
    

    所以你可以看到 Mainwindow 正在与多个视图模型对话,Main 是它自己的视图模型,它是它的数据上下文,它还引用了 otherviewmodel1 和 otherviewmodel2。希望这会有所帮助,干杯!

    【讨论】:

    • 这不能回答问题。 OP 想了解 collection 控件中的数据模板。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多