Using StaticResource for Dictionary on XAML

Asked 2 years ago, Updated 2 years ago, 61 views

In Windows 10, Visual Studio 2017, and .NET Framework 4.5, we created DataTemplateSelectors similar to the following:

 ContentProperty("DataTemplateTable")
public class TypeToDataTemplateSelector:DataTemplateSelector
{
    publicTypeToDataTemplateDictionaryDataTemplateTable {get;set;}

    public override DataTemplate SelectTemplate (object item, DependencyObject container)
    {
        // Obtaining DataTemplate from DataTemplateTable
    }
}

public classTypeToDataTemplateDictionary:Dictionary<Type,DataTemplate>{}

The code below worked fine.

<local:TypeToDataTemplateSelector x:Key="TypeToDataTemplateSelector">
    <local:TypeToDataTemplateDictionary>
        <DataTemplate x:Key="{x:Type local:ViewModelA}"DataType="local:ViewModelB">
            <TextBlock Text="ViewModelA"/>
        </DataTemplate>
        <DataTemplate x:Key="{x:Type local:ViewModelB}"DataType="local:ViewModelB">
            <TextBlock Text="ViewModelB"/>
        </DataTemplate>
        <DataTemplate x:Key="{x:Type local:ViewModelC}"DataType="local:ViewModelC">
            <TextBlock Text="ViewModelC"/>
        </DataTemplate>
    </local:TypeToDataTemplateDictionary>
</local:TypeToDataTemplateSelector>

However, there was a problem using StaticResource.

<DataTemplate x:Key="DataTemplateA"DataType="local:ViewModelA">
    <TextBlock Text="ViewModelA"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplateB"DataType="local:ViewModelB">
    <TextBlock Text="ViewModelB"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplateC"DataType="local:ViewModelC">
    <TextBlock Text="ViewModelC"/>
</DataTemplate>
<local:TypeToDataTemplateSelector x:Key="TypeToDataTemplateSelector">
    <local:TypeToDataTemplateDictionary>
        <StaticResource x:Key="{x:Type local:ViewModelA}"ResourceKey="DataTemplateA"/>
        <StaticResource x:Key="{x:Type local:ViewModelB}"ResourceKey="DataTemplateB"/>
        <StaticResource x:Key="{x:Type local:ViewModelC}"ResourceKey="DataTemplateC"/>
    </local:TypeToDataTemplateDictionary>
</local:TypeToDataTemplateSelector>

The build passes, but the XamlObjectWriterException: 'StaticResourceHolder' object does not have a key value at runtime.' Line number 'xx', line position 'xx'. and exception occur.

Can we somehow avoid this and use StaticResource for Dictionary?

c# wpf

2022-09-30 11:37

1 Answers

Doesn't it just mean "{x:Type local:ViewModelA}" can't be used as a key value?


2022-09-30 11:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.