zyash
zyash

Reputation: 732

Applying a DataTemplateSelector to a single Item

I have created a DataTemplateSelector class. I would like to apply it to a single item, so it chooses a template based on some conditions.

Essentially I'd like to have the equivalent of this in xaml:

% if myitem.A
  <TextBlock Text="{Binding myitem.data }"/>
% else if myitem.B
  <Button Content="{Binding myitem.data }"/>

 public class MyTemplateSelector : DataTemplateSelector
    {

        public DataTemplate A {
            get;
            set;
        }

        public DataTemplate B {
            get;
            set;
        }


        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            var myitem = item as MyItem;
            if (myitem.A)
               return A;
            else if (myitem.B)
               return B;
            return base.SelectTemplate(item, container);
        }

    }

How can I achieve this?

Thanks.

Upvotes: 1

Views: 1864

Answers (1)

Ku6opr
Ku6opr

Reputation: 8126

If you have one item, not a list of items, you can use ContentPresenter with a custom ContentTemplate to show this item. ContentTemplate can use your TemplateSelector as you know:

       <ContentPresenter x:Name="control">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>
                    <local:MyTemplateSelector Content="{Binding}">
                        <local:MyTemplateSelector.A>
                            <DataTemplate>
                                <TextBlock Text="null" />
                            </DataTemplate>
                        </local:MyTemplateSelector.A>
                        <local:MyTemplateSelector.B>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" />
                            </DataTemplate>
                        </local:MyTemplateSelector.B>
                    </local:MyTemplateSelector>
                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>

This is my TemplateSelector:

public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item == null)
            return A;

        return B;
    }

And this line add some content to display:

control.Content = "123";

Upvotes: 4

Related Questions