Dynamically Load Content with WPF

泪湿孤枕 提交于 2019-12-06 06:55:20

I've used the following method to force re-application of a DataTemplateSelector.

Derive from ObservableCollection and add a method that raises NotifyCollectionChangedEventArgs with NotifyCollectionChangedAction.Reset.

public class MyThingCollection : ObservableCollection<MyThing>
{
    public void RaiseResetCollection()
    {
        OnCollectionChanged(new 
            NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

Your view model exposes an instance of this type and your ItemsControl binds to that.

public class MyViewModel : ... (view model base)
{
    public MyThingCollection Items{get; private set;}
}

<ItemsControl
     ItemsSource="{Binding Items}"
     ItemsTemplateSelector="{StaticResource MyTemplateSelector}"
     ...

When you need your DataTemplateSelector to be re-applied call RaiseResetCollection on the collection.

I generally use DataTemplateSelector like this

public class MyTemplateSelector : DataTemplateSelector
{
    public DataTemplate Template1 { get; set; }
    public DataTemplate Template2 { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        ... return Template1 or Template2 depending on item
    }
    ...
}

<DataTemplate x:Key="MyTemplate1" DataType="{x:Type MyType1}">
    ...
</DateTemplate>

<DataTemplate x:Key="MyTemplate2" DataType="{x:Type MyType2}">
    ...
</DateTemplate>

<local:MyTemplateSelector 
    x:Key="MyTemplateSelector" 
    Template1="{StaticResource MyTemplate1}"
    Template2="{StaticResource MyTemplate2}"
/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!