WPF将路径绑定到类的typename [英] WPF binding a path to the typename of a class

查看:84
本文介绍了WPF将路径绑定到类的typename的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用WPF,我想将GroupBox的标题绑定到多态类的类型名。所以如果我有一个名为Element的类,以及派生自Element的两个类,例如BasicElement和AdvancedElement,我希望GroupBox的标题表示BasicElement或AdvancedElement。这是我用于GroupBox的xaml。它是由ItemsControl使用的DataTemplate的一部分。我希望在XAML中代替Path = DerivedTypeNameOf(group),其中group是组数组中的每个组。

Using WPF, I want to bind the header of a GroupBox to the typename of a polymorphic class. So if I have a class called Element, and two classes that derive from Element, such as BasicElement and AdvancedElement, I want the header of the GroupBox to say "BasicElement" or "AdvancedElement". Here is the xaml I am using for the GroupBox. It's part of a DataTemplate being used by an ItemsControl. I'm hoping for something in place of Path=DerivedTypeNameOf(group) in the XAML, where group is each group in the groups array.

请注意,TheData的ObjectInstance正在设置为GroupSet的有效实例,该实例包含一些BasicGroups和AdvancedGroups的数组。

Note that the ObjectInstance of TheData is being set to a valid instance of GroupSet which holds an array of some BasicGroups and AdvancedGroups.

以下是相关的代码隐藏类:

Here are the pertinent code-behind classes:

public class Group
{
    public string groupName;

    public string df_groupName
    {
        get { return this.groupName; }
        set { this.groupName = value; }
    }
}

public class BasicGroup : Group
{

}

public class AdvancedGroup : Group
{

}

public class GroupSet
{
    public Group [] groups;

    public Group [] df_groups
    {
        get { return this.groups; }
        set { this.groups = value; }
    }
};

这是XAML:

<UserControl.Resources>
    <ResourceDictionary>
        <ObjectDataProvider x:Key="TheData" />

        <DataTemplate x:Key="GroupTemplate">
            <GroupBox Header="{Binding Path=DerivedTypeNameOf(group)}">
                <TextBox Text="This is some text"/>
            </GroupBox>
        </DataTemplate>

    </ResourceDictionary>
</UserControl.Resources>

    <ItemsControl ItemsSource="{Binding Source={StaticResource TheData}, Path=groups}" ItemTemplate="{StaticResource GroupTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>


推荐答案

为什么不添加

public abstract string DerivedTypeName { get; set; }

到您的基类,并为每个派生类型覆盖它,那么您只需绑定到一个字符串。

to your base class and override it for each derived type then you are simply binding to a string.

这篇关于WPF将路径绑定到类的typename的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆