可以包含其他控件的C#用户控件(使用时)

Mic*_*and 6 c# wpf user-controls

我在ASP中发现了一些关于这个问题的东西,但它对我帮助不大......

我想做的是以下内容:我想创建一个用户控件,它具有一个集合作为属性和按钮来浏览此集合.我希望能够将此用户控件绑定到一个集合并在其上显示不同的控件(包含该集合中的数据).就像你在表格下边缘的MS Access中所拥有的一样......

更确切地说:

当我实际使用我的应用程序的控制(后我创造了它),我希望能够以多个控件之间添加到它(文本框,标签等)<myControly></mycontrol> 如果我现在要做的是,在我的用户控件的控件消失.

Nir*_*Nir 8

以下是一种实现您想要的方法的示例:

首先,代码 - 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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

用户控件的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>
Run Code Online (Sandbox Code Playgroud)

最后,xaml使用我们精彩的新控件:

<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>
Run Code Online (Sandbox Code Playgroud)