Question

I have an MarkupExtension

public class DataTemplates : Dictionary<object, DataTemplate>{}

[MarkupExtensionReturnType(typeof(DataTemplateSelector))]
[ContentProperty("DataTemplatesDictionary")]
public class TemplateSelectorExtension : MarkupExtension
{
  //...
  public DataTemplates DataTemplatesDictionary { get; set; }

  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    if (DataTemplatesDictionary == null) throw new ArgumentException();
    // some logic
  }
}

Use it in xaml

<TabControl.ItemTemplateSelector>
  <GUI:TemplateSelector>
    <GUI:DataTemplates> <!-- How do I avoid this element???-->

      <DataTemplate ....>
      </DataTemplate>
      <DataTemplate ....>
      </DataTemplate>

    </GUI:DataTemplates>
  </GUI:TemplateSelector>
</TabControl.ItemTemplateSelector>

The question is: is it possible to avoid "GUI:DataTemplates" element writing some TypeConverter or somehow else?

thanks!

UPDATE: I've found MSDN article, it states that my example should work without "GUI:DataTemplates" well, but it doesn't :( Also many articles in the internet state the same. What do I do wrong?

Était-ce utile?

La solution

The problem is that you're using a Dictionary which gets you stuck between two conflicting requirements. You removed some key parts of the code so I'm just guessing at what else is there, but using the exploded syntax (<GUI:DataTemplates>) you're explicitly setting up the Dictionary in XAML and so you can assign x:Key attributes on each to be used as the keys in the dictionary.

Falling back to the ContentProperty usage though you still need to assign a key for each dictionary item, but XAML won't let you declare x:Key outside of a dictionary and can't identify the implicit one used by the MarkupExtension. You also can't just leave the DataTemplate key off completely because then the Dictionary has no keys. You could use DataType attributes in this case but since you could only have one per type anyway you would be better off not using the selector at all and just putting those in the TabControl's Resources and letting the implicit typing handle the templates automatically.

If you can switch to using a normal collection instead of the dictionary and do selection based on index or something like that you would be able to strip out the extra element but given the minimal amount of XAML you're trying to removing I'd just live with it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top