【问题标题】:WPF List of BaseClass Items and their visibilityWPF BaseClass 项目列表及其可见性
【发布时间】:2013-11-04 08:13:18
【问题描述】:

我有以下问题

public abstract class ParentClass
{
 public int Field{get;set;}
}

public class ChildrenClass1 : ParentClass
{
public int Field2{get;set;}
}
public class ChildrenClass2 : ParentClass
{
public int Field3{get;set;}
}

不,我有 ParentClass 的列表。

List<ParentClass> Parents = new List<ParentClass>();

我像这样将它绑定到列表框。

<ListBox ItemsSource = "{Binding Parents}"/>

现在如果它是 ChildrenClass1 类型,我想显示 Field2,如果是 ChildrenClass2,我想在 ListBox ItemTemplate 中显示 Field3。

我想到的第一个解决方案是这样做:

<ListBox ItemsSource = "{Binding Parents}"/>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text = "{Binding Converter = {StaticResource Converter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

转换器应该检查项目的类型,如果是 ChildrenClass1,则返回 Field2,依此类推。

但我认为这是解决方法而不是解决方案。有什么可以检查 xaml 中的类型或类似的东西吗?你如何解决这个问题?

编辑:如果我想大幅改变 DataTemplate 而不仅仅是一个字段,情况会怎样?上述解决方法将毫无用处。此问题的解决方法是使用不同的 DataTemplate 制作 2 个 ListBox,并使用转换器检查实际 typeof 项来设置可见性。但它会产生许多绑定错误并生成 2 个列表框而不是一个,这会减慢我们的应用程序的速度。

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

    您可以为每种类型创建两个 DataTemplate,而 WPF 将发挥一切魔力。

    <DataTemplate DataType="{x:Type namespace:ChildrenClass1}">
    <TextBlock Text="{Binding Field2}"/>
    </DataTemplate>
    
     <DataTemplate DataType="{x:Type namespace:ChildrenClass2}">
    <TextBlock Text="{Binding Field3}"/>
    </DataTemplate>
    

    【讨论】:

    • 天才,这正是我所需要的!:) 谢谢!
    猜你喜欢
    • 2014-05-28
    • 2014-07-08
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2014-03-21
    相关资源
    最近更新 更多