ua741
ua741

Reputation: 1466

How to trigger datatemplate selector in Windows Phone?

I have a property and depending upon it's state (say A and B) I either show a usercontrol of animation or a image.

Now, if the property changes, I want to trigger the datatemplate selector again. On searching, I found that in WPF I could have used DataTemplate.Trigger but it's not available in WP.

So, my question is

Also, as there are only two states, if think I can use Converter to collapse the visibility. For basic if else situation, I will need to write two converters.( Can I somehow do it using one converter only?) Here is the exact situation.

If state == A :

select userControl_A

else : select userControl_B

Also,

EDIT- Just realized, I can use parameter object to write just one converter.

Upvotes: 0

Views: 1039

Answers (1)

Olivier Payen
Olivier Payen

Reputation: 15268

You could implement a DataTemplateSelector like described here.
I use it and it works pretty well.

EDIT:
If you need to update the DataTemplate when the property changes, you should subscribe to the PropertyChanged event of the data object in the TemplateSelector and execute the SelectTemplate method again.

Here is the code sample:

public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
    City itemAux = item as City;

    // Subscribe to the PropertyChanged event
    itemAux.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(itemAux_PropertyChanged);

    return GetTemplate(itemAux, container);
}

private DataTemplate GetTemplate(City itemAux, DependencyObject container)
{
    if (itemAux != null)
    {
        if (itemAux.Country == "Brazil")
            return BrazilTemplate;
        if (itemAux.Country == "USA")
            return UsaTemplate;
        if (itemAux.Country == "England")
            return EnglandTemplate;
    }

    return base.SelectTemplate(itemAux, container);
}

void itemAux_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    // A property has changed, we need to reevaluate the template
    this.ContentTemplate = GetTemplate(sender as City, this);
}

Upvotes: 3

Related Questions