How to trigger datatemplate selector in Windows Phone?

冷暖自知 提交于 2020-01-17 02:22:27

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/13467018/how-to-trigger-datatemplate-selector-in-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!