Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建可嵌套对象_C#_Xaml_Silverlight 4.0_Wpf Controls - Fatal编程技术网

C# 如何创建可嵌套对象

C# 如何创建可嵌套对象,c#,xaml,silverlight-4.0,wpf-controls,C#,Xaml,Silverlight 4.0,Wpf Controls,一开始我想打个招呼,所以。。。你好我需要创建一个嵌套对象结构。 我有这样一个对象(xaml页面) <navigation:Page x:Class="ItemTemplateExample.ContentItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

一开始我想打个招呼,所以。。。你好我需要创建一个嵌套对象结构。 我有这样一个对象(xaml页面)

<navigation:Page x:Class="ItemTemplateExample.ContentItem" 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d"
       xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
       d:DesignWidth="200" d:DesignHeight="20"
       Title="ContentItem Page">
<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="button1" />
    <ContentControl  Grid.Column="1" x:Name="content1" />
</Grid>

现在我想在嵌套结构中使用它。比如说

<local:ContentItem ButtonText="level 1">
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2">
          <local:ContentItem ButtonText="level 3" />    
     </local:ContentItem>
</local:ContentItem>


其中ButtonText将是已知值(在添加嵌套对象时设置),每个对象的内容将是相同类型的对象。我不知道如何开始。请给我一些提示,埃克斯梅普斯。谢谢。

您希望在WPF中看到HierarchycalDataTemplate


两种可能的解决方案:用户控件或数据模板。用户控件可能是最简单的方法,但从长远来看,数据模板可能是更好的解决方案

将用户控件添加到项目很简单-VisualStudio有一个模板。您可以在
ContentItem
用户控件的Xaml中放置与此处显示的完全相同的
Grid
。然后只需要在用户控件的codebehind中定义一个名为
ButtonText
的属性。这应该做到:

public string ButtonText
{
    get { return button1.Content.ToString(); }
    set { button1.Content = value; }
}
这应该让您或多或少地像您所展示的那样使用Xaml


我建议使用数据模板可能更好的原因是,您可能不想在Xaml中硬编码嵌套结构。能够从数据生成这样的结构,而不是将其烘焙到UI中,这通常是很好的。但是,如果您的结构完全固定,您所要求的方法可能是可以的。

可能相关:

谢谢,但我期望有所不同。您期望什么,您希望它以什么方式不同?我很想提供帮助,但你的反馈不够具体。最后,我用了treeview和我自己的模板。如果我知道该搜索什么,那就太容易了。