質問

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

  • Is their a way to trigger datatemplate selector so when property changes from state A to B, then appropriate usercontrol gets selected. If yes, then please give some example how to implement it.

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,

  • Will the animation usercontrol will effect the performance when it's in Collapsed state?

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

役に立ちましたか?

解決

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top