No estoy seguro acerca de reemplazar el valor por defecto DataTemplate, pero se puede usar un ValueConverter pasar ToString pantalla en el caso de ciertos tipos y una cadena vacía de lo contrario. Aquí hay algo de código (nótese que el imposible de TypeB bloque de texto tiene el convertidor en él para mostrar cómo se ve normalmente):
.xaml:
<Window x:Class="EmptyTemplate.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:EmptyTemplate"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<loc:AType x:Key="atype"/>
<loc:BType x:Key="btype"/>
<loc:TypeConverter x:Key="TypeConverter"/>
</Window.Resources>
<StackPanel>
<Button Content="{Binding Source={StaticResource atype}, Converter={StaticResource TypeConverter}}"/>
<Button Content="{Binding Source={StaticResource btype}, Converter={StaticResource TypeConverter}}"/>
<TextBlock Text="{Binding Source={StaticResource atype}, Converter={StaticResource TypeConverter}}"/>
<TextBlock Text="{Binding Source={StaticResource btype}}"/>
</StackPanel>
</Window>
.xaml.cs:
namespace EmptyTemplate
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
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
}
}
"WPF coincide con un objeto con su DataTemplate por tipo de tiempo de ejecución exacta" - No es cierto. Si agrega un DataTemplate con DataType = BaseClass, también coincidirá con SubClass. Lo he visto funcionar Desafortunadamente, el marco no permite específicamente la creación de un DataTemplate para System.Object; obtienes un error de tiempo de ejecución "El tipo 'DataTemplateKey' falló construcción. DataTemplate.DataType no puede ser tipo Object". –
Tienes razón. Estaba pensando en Styles, que no son heredados automáticamente. Actualizando mi respuesta. Gracias. –