【问题标题】:Using an Abstract Class as DataType in DataTemplates在 DataTemplates 中使用抽象类作为 DataType
【发布时间】:2014-03-05 11:20:26
【问题描述】:

我偶然发现了有关 C# 中抽象类和 DataTemplates 的其他 StackOverflow 问题,但不知何故我无法让它工作。

代码如下:

public abstract class AbstractParser() {
    public string Name { get; set; }
}

public class ConcreteParser() : AbstractParser { }

现在,我想使用抽象类创建一个 DataTemplate(对于 ListBox,包含 ConcreteParser 的元素。 但是,我无法让它在DataTemplate 中工作。根据其他帖子(例如 WPF databinding to interface and not actual object - casting possible? ),这应该是可能的:

<DataTemplate DataType="{x:Type local:AbstractParser}" />

提出一个具体的问题:

如果我想为包含许多不同具体类的对象的ListBox 创建一个模板,这些对象都派生自一个通用抽象基类,那么最好的选择是什么?属性都在抽象基类中定义。

【问题讨论】:

    标签: c# wpf abstract-class datatemplate


    【解决方案1】:

    我不知道这是否仍然相关,但我只是想知道同样的事情。 您可以为 Abstract types 创建一个 DataTemplate 。

    这是我创建的测试仪:

    CS:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }
    
        public Base Base
        {
            get { return new Child(); }
        }
    
        public List<Base> BaseCollection
        {
            get { return new List<Base> { new Child(), new Child(), new Child2(), new Child2() }; }
        }
    }
    
    public abstract class Base
    {
        public virtual string Name
        {
            get { return "I'm a Base class"; }         
        }        
    }
    
    public class Child : Base
    {
        public override string Name
        {
            get { return "I'm A child"; }
        }
    }
    
    public class Child2 : Base
    {
    
    }
    

    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>
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2010-11-18
      • 2016-02-01
      • 2013-10-15
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多