Specify a default empty DataTemplate instead of the default 'ToString()' DataTemplate

前端 未结 6 1371
囚心锁ツ
囚心锁ツ 2021-02-19 10:11

The default DataTemplate in a wpf application displays the result of the .ToString() method. I\'m developing an application where the default DataTemplate should di

6条回答
  •  一生所求
    2021-02-19 11:12

    Here a working example about how to do this using a selector (the best way IMO):

    public class EmptyDefaultDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item != null)
            {
                var dataTemplateKey = new DataTemplateKey(item.GetType());
                var dataTemplate = ((FrameworkElement) container).TryFindResource(dataTemplateKey);
                if (dataTemplate != null)
                    return (DataTemplate) dataTemplate;
            }
    
            return new DataTemplate(); //null does not work
        }
    }
    

提交回复
热议问题