c# - 如何在 XAML 中显示递归属性

标签 c# wpf xaml

我有一个类,看起来像

public class MyClass 
{
    public string MyTitle{get;set;}
    public MyClass Child{get;set;
}

这样做的原因是 child 和 parent 之间永远只有一对一的关系(也就是说,没有 parent 会有多个 child )。

我想将其放置在 WPF 应用程序中,其中每个 MyTitle 都将水平显示(基于总共有多少个父项和子项)。 EG,类似

MyClass.MyTitle       MyClass.Child.MyTitle       MyClass.Child.Child.MyTitle  etc

在网络世界中,我们可以添加循环和 if 语句,只需检查子项是否为 null,然后附加下一项。

在网络世界中,类似于(伪代码)

item = Model.MyClass;

do while(true) {    
    if (item != null) {
        <div class="floatLeft">item.MyTitle</div>
    }
    else {
        break;
    }
    item = parent.Child;
}

XAML 似乎将我限制为模板。虽然我确定我会制定一个 C# 解决方案然后直接绑定(bind),但我正在利用这个机会来了解有关 XAML 的更多信息。

问题是,它不是一个列表,所以我不确定使用 ItemsControl/ListView/etc 是否是正确的方法。我什至不确定我想要的是否可以完成。

所以我的问题是这是否可以仅使用 XAML 来完成?

最佳答案

如下所示的一个简单的 DataTemplate 就可以完成这项工作。通过设置它的DataType属性,当Content的类型匹配DataType时,它会自动应用到ContentPresenters、ContentControls等的Content上,这也是递归的.

<Window.Resources>
    <DataTemplate DataType="{x:Type local:MyClass}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Margin="4" Text="{Binding MyTitle}"/>
            <ContentPresenter Content="{Binding Child}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

鉴于您的窗口的 DataContext 包含一个 MyClass 实例,您可以只写

<ContentControl Content="{Binding}"/>

并且 DataTemplate 将自动递归应用。

您可以尝试像这样设置 DataContext

DataContext = new MyClass
{
    MyTitle = "Item1",
    Child = new MyClass
    {
        MyTitle = "Item2",
        Child = new MyClass
        {
            MyTitle = "Item3",
        }
    }
};

关于c# - 如何在 XAML 中显示递归属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788501/

相关文章:

WPF 路径命令

xaml - XAML 资源字典中的算术运算

wpf - 刷新数据网格项而不丢失所选行 - XAML

c# - 如何在C#中存储https POSTmethod的返回值

c# - 使用 Ninject 在类中注入(inject)字符串属性

c# - Prism RequestNavigate 在启动时立即从 PrismApplication 导航

wpf - 如何在我的 UserControl 中接受剪贴板中的粘贴?

c# - 将文件发送到回收站

c# - 使用按位方法对相同类型的值进行理想的 c# 缩减方法?

WPF 数据网格 : Resource per row?