Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# User Control that can contain other Controls (when using it)

I found something about this issue for ASP, but it didn't help me much ...

What I'd like to do is the following: I want to create a user control that has a collection as property and buttons to navigate through this collection. I want to be able to bind this user control to a collection and display different controls on it (containing data from that collection). Like what you had in MS Access on the lower edge of a form ...

to be more precise:

When I actually use the control in my application (after I created it), I want to be able to add multiple controls to it (textboxes, labels etc) between the <myControly> and </mycontrol> If I do that now, the controls on my user control disappear.

like image 593
Michael Niemand Avatar asked Jun 09 '09 12:06

Michael Niemand


2 Answers

Here is an example of one way to do what you want:

First, the code - UserControl1.xaml.cs

public partial class UserControl1 : UserControl
{
    public static readonly DependencyProperty MyContentProperty =
        DependencyProperty.Register("MyContent", typeof(object), typeof(UserControl1));


    public UserControl1()
    {
        InitializeComponent();
    }

    public object MyContent
    {
        get { return GetValue(MyContentProperty); }
        set { SetValue(MyContentProperty, value); }
    }
}

And the user control's XAML - UserControl1.xaml

<UserControl x:Class="InCtrl.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300" Name="MyCtrl">
    <StackPanel>
        <Button Content="Up"/>
        <ContentPresenter Content="{Binding ElementName=MyCtrl, Path=MyContent}"/>
        <Button Content="Down"/>
    </StackPanel>
</UserControl>

And finally, the xaml to use our wonderful new control:

<Window x:Class="InCtrl.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:me="clr-namespace:InCtrl"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <me:UserControl1>
            <me:UserControl1.MyContent>
                <Button Content="Middle"/>
            </me:UserControl1.MyContent>
        </me:UserControl1>
    </Grid>
</Window>
like image 186
Nir Avatar answered Oct 01 '22 21:10

Nir


I'm having a hard time understanding your question, but I think what you're describing is an ItemsControl using DataTemplates to display the contents of (presumably) an ObservableCollection(T).

like image 29
Greg D Avatar answered Oct 01 '22 20:10

Greg D