首页 > 解决方案 > 为什么 ListBox ItemTemplateSelector="{StaticResource MyDataTemplateSelector}" 不能与资源一起使用?

问题描述

主题:我正在通过使用此处找到的 Microsoft 示例来学习 DataTemplate 概念:https: //docs.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview 和 GitHub 上的此处:https ://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/DataTemplatingIntro

问题:Xaml 设计窗口显示错误。

错误:NullReferenceException:对象引用未设置为对象的实例。

并从堆栈顶部异常:

在 BindingTest.TaskListDataTemplateSelector.SelectTemplate(对象项,DependencyObject 容器)

细节:创建类TaskListDataTemplateSelector并添加这两行后出现错误:

<Window.Resources>

    <local:TaskListDataTemplateSelector x:Key="MyDataTemplateSelector"/>

</Window.Resources>

<ListBox ....

   ItemTemplateSelector="{StaticResource MyDataTemplateSelector}"

</ListBox>

更多信息:微软的例子也有同样的问题。

Window x:Class="BindingTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BindingTest"
    mc:Ignorable="d"
    Title="MainWindow"  Width="525" SizeToContent="WidthAndHeight">

<Window.Resources>
    <local:Tasks x:Key="myTodoList"/>
    <local:TaskListDataTemplateSelector x:Key="MyDataTemplateSelector"/>

    <DataTemplate x:Key="importantTaskTemplate">
        <DataTemplate.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="FontSize" Value="20"/>
            </Style>
        </DataTemplate.Resources>
        <Border Name="border" BorderBrush="Red" BorderThickness="1"
                Padding="5" Margin="5">
            <DockPanel HorizontalAlignment="Center">
                <TextBlock Text="{Binding Path=Description}"/>
                <TextBlock>!</TextBlock>
            </DockPanel>
        </Border>
    </DataTemplate>

    <DataTemplate x:Key="myTaskTemplate">
        <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
               Padding="5" Margin="5">
            <Grid ShowGridLines="false">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Row="0" Grid.Column="0"  Text="Task Name:"/>
                <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Name}"/>
                <TextBlock Grid.Row="1" Grid.Column="0"  Text="Description:"/>
                <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
                <TextBlock Grid.Row="2" Grid.Column="0"  Text="Priority:"/>
                <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
            </Grid>
        </Border>

        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=TaskType}">
                <DataTrigger.Value>
                    <local:TaskType>Home</local:TaskType>
                </DataTrigger.Value>
                <Setter TargetName="border" Property="BorderBrush" Value="Yellow"/>
            </DataTrigger>
        </DataTemplate.Triggers>

    </DataTemplate>
</Window.Resources>

<Grid>
    <StackPanel>
        <TextBlock FontSize="20" Text="My Task List"/>

        <ListBox Width="400" Margin="10"
                 ItemsSource="{Binding Source={StaticResource myTodoList}}"
                 ItemTemplateSelector="{StaticResource MyDataTemplateSelector}"
                   HorizontalContentAlignment="Stretch">
        </ListBox>
    </StackPanel>

</Grid>

 public   class TaskListDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate
      SelectTemplate(object item, DependencyObject container)
    {
        if (item != null && item is Task)
        {
            var taskitem = (Task)item;
            var window = Application.Current.MainWindow;
            if (taskitem.Priority == 1)
                return
                    window.FindResource("ImportantTaskTemplate") as DataTemplate;
            return
                window.FindResource("MyTaskTemplate") as DataTemplate;
        }

        return null;
    }
}

标签: c#datatemplateitemtemplateselector

解决方案


我发现了一个错误。这是一个拼写问题:特别是大写。

MyTaskTemplate 和 ImportantTaskTemplate 的拼写在整个项目中并不一致。

该项目现在编译并运行,但在 Xaml 设计窗口中仍然出现相同的异常。

更多挖掘揭示了 Xaml 设计窗口中 Null Reference Exception 错误的修复。感谢 Chris Anderson 和他的书:Essential Windows Presentation Foundation 第 341 页。将 TaskListDataTemplateSelector 替换为:

 public class TaskListDataTemplateSelector : DataTemplateSelector
{

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item != null && item is Task)
        {
            var taskitem = (Task)item;
            var window = Application.Current.MainWindow;
            if (taskitem.Priority == 1)
                return ((FrameworkElement)container).FindResource
                    ("ImportantTaskTemplate") as DataTemplate;

            return
            ((FrameworkElement)container).FindResource
                    ("MyTaskTemplate") as DataTemplate;
        }
        return null;
    }
}

推荐阅读