Conditional List itemtemplate or datatemplate in WPF

后端 未结 2 2105
北荒
北荒 2020-12-01 05:42

This may be an obvious question, but I think there may well be multiple ways to implement it, so not only will this be useful to me, hopefully it will be useful to others.

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 06:17

    One option is to create a DataTemplateSelector in your code:

    public class QueueDisplayDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
    
            var listBoxItem = item as JobQueueListBoxItem;
            var resourceName = String.Empty;
            switch (listBoxItem.JobQueueListBoxItemType)
            {
                case JobQueueListBoxItemType.QueuedJob :
                    resourceName = "DataTemplateQueuedJob";
                    break;
                case JobQueueListBoxItemType.TransferWorker :
                    resourceName = "DataTemplateTransferWorker";
                    break;
                default:
                    throw new InvalidOperationException(string.Format("There is no corresponding list box template for {0}", listBoxItem.JobQueueListBoxItemType));
            }
            var element = container as FrameworkElement;
            return element.FindResource(resourceName) as DataTemplate;
        }
    }
    

    This would then be declared in your XAML as a resource

            
                
    

    And then you would assign this to you list box:

        
    

提交回复
热议问题