为什么要在ListView中使用DataTemplate

本文关键字:DataTemplate ListView 为什么 | 更新日期: 2024-10-19 06:22:11

如果我使用XAML中ListView内部的DataTemplate

我使用了ListView来显示来自ObservableCollection的内容,而不使用DataTemplate,而使用DataTemplate看起来完全一样?

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

为什么要在ListView中使用DataTemplate

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>

太酷了!您可以在模板中放入任何,因此它使ItemsControl(及其派生类)成为WPF中最强大的类。

请在这里查看#HighCore的答案WPF MVVM为什么使用ContentControl+DataTemplate视图而不是直接的XAML窗口视图?。

 <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是它自己的视图模型,它是它的数据上下文,它还引用了其他视图模型1和其他视图模型2。希望这有帮助,干杯!