C# 在DataTemplates中将抽象类用作数据类型
我已经回答了其他关于C#中的抽象类和数据模板的StackOverflow问题,但不知何故,我没有让它起作用 代码如下所示:C# 在DataTemplates中将抽象类用作数据类型,c#,wpf,abstract-class,datatemplate,C#,Wpf,Abstract Class,Datatemplate,我已经回答了其他关于C#中的抽象类和数据模板的StackOverflow问题,但不知何故,我没有让它起作用 代码如下所示: public abstract class AbstractParser() { public string Name { get; set; } } public class ConcreteParser() : AbstractParser { } 现在,我想使用抽象类(对于ListBox)创建一个数据模板,其中包含ConcreteParser的元素。 但是
public abstract class AbstractParser() {
public string Name { get; set; }
}
public class ConcreteParser() : AbstractParser { }
现在,我想使用抽象类(对于ListBox
)创建一个数据模板,其中包含ConcreteParser
的元素。
但是,我无法在数据模板中使用它。根据其他帖子(例如),这应该是可能的:
<DataTemplate DataType="{x:Type local:AbstractParser}" />
要提出一个具体问题:
如果我想为一个包含许多不同具体类的对象的列表框创建一个模板,这些对象都是从一个公共抽象基类派生出来的,那么最好的选择是什么呢?属性都是在抽象基类中定义的。我不知道这是否仍然相关,但我只是想知道同样的问题惯性导航与制导。
您可以为抽象类型创建数据模板
下面是一个测试仪iv'e创建:
政务司司长:
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
this.DataContext=this;
}
公共基地
{
获取{return new Child();}
}
公共列表基集合
{
获取{返回新列表{new Child(),new Child(),new Child2(),new Child2()};}
}
}
公共抽象类基
{
公共虚拟字符串名
{
获取{return“我是基类”;}
}
}
公共类子类:基
{
公共重写字符串名
{
获取{返回“我是个孩子”;}
}
}
公共类Child2:基本类
{
}
XAML:
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Base}">
<TextBlock Foreground="Red" FontSize="24" Text="{Binding Name}" />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<ContentControl Content="{Binding Base}" HorizontalAlignment="Center" VerticalAlignment="Center" Height="30" Width="100" />
<ItemsControl ItemsSource="{Binding BaseCollection}" Grid.Row="2"/>
</Grid>
</Window>
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Base}">
<TextBlock Foreground="Red" FontSize="24" Text="{Binding Name}" />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<ContentControl Content="{Binding Base}" HorizontalAlignment="Center" VerticalAlignment="Center" Height="30" Width="100" />
<ItemsControl ItemsSource="{Binding BaseCollection}" Grid.Row="2"/>
</Grid>
</Window>