io non sono sicuro di sostituire il default DataTemplate, ma è possibile utilizzare un ValueConverter per passare visualizzazione ToString nel caso di determinati tipi e una stringa vuota altrimenti. Ecco po 'di codice (si noti che il doesnt TypeB blocco di testo ha il convertitore sopra per vedere che cosa assomiglia 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
}
}
fonte
2009-04-03 23:56:59
"WPF corrisponde a un oggetto con la sua DataTemplate da esatto tipo di runtime" - Non è vero. Se si aggiunge un DataTemplate con DataType = BaseClass, corrisponderà anche alla sottoclass. L'ho visto funzionare. Sfortunatamente, il framework non consente in modo specifico di creare un DataTemplate per System.Object; si ottiene un errore di runtime "La costruzione del tipo" DataTemplateKey "non è riuscita. DataTemplate.DataType non può essere di tipo Object." –
Hai ragione. Stavo pensando agli stili, che non vengono automaticamente ereditati. Aggiornamento della mia risposta. Grazie. –