开发者

How to create nestable object

At the begining I would like to say hello, so ... Hello. I need to create a nested object structure. I've got an object (xaml page) like this

<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"&g开发者_如何学Ct;
<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>

Now I would like to use it in nested structure. For Example

<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>

Where ButtonText will be known value (set when adding nested object) and Content of each object will be object of the same type. I have no idea how to start. Please give me some hint, exmaples. Thank You.


you would like to see HierarchicalDataTemplate in WPF

Seee here


Two possible solutions: a user control or a data template. The user control is probably the simplest to get to from where you are now, but the data template may be a better solution in the long run.

Adding a user control to a project is straightforward - Visual Studio has a template for that. You could just put the exact same Grid you've shown here inside your ContentItem user control's Xaml. And then you'd just need to define a property called ButtonText in the codebehind of your user control. This should do it:

public string ButtonText
{
    get { return button1.Content.ToString(); }
    set { button1.Content = value; }
}

That should let you use Xaml more or less exactly like you've shown.

The reason I'm suggesting that a data template might be better is that you might not want to hard-code the nested structure in Xaml. It's often nice to be able to generate such structure from data rather than baking it into the UI. However, if your structure is completely fixed, the approach you've asked for is probably OK.


Possibly related:Example of Nested Collections

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜