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

前端 未结 6 1342
囚心锁ツ
囚心锁ツ 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:02

    I'm not sure about replacing the default DataTemplate, but you can use a ValueConverter to pass display ToString in the case of certain types and an empty string otherwise. Here's some code (note that the typeb textblock doesnt have the converter on it to show what it looks like normally):

    .xaml:

    
        
            
            
            
        
        
            

    .xaml.cs:

    namespace EmptyTemplate
    {
        /// 
        /// Interaction logic for Window1.xaml
        /// 
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
            }
        }
    
        public class AType { }
    
        public class BType { }
    
        public class TypeConverter : IValueConverter
        {
            public DataTemplate DefaultTemplate { get; set; }
    
            #region IValueConverter Members
    
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value.GetType() == typeof(AType))
                {
                    return value.ToString();
                }
                return DefaultTemplate;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    
            #endregion
        }
    }
    

提交回复
热议问题