可以包含其他控件的 C# 用户控件(使用时) [英] C# User Control that can contain other Controls (when using it)
问题描述
我为 ASP 找到了有关此问题的一些信息,但对我没有太大帮助...
I found something about this issue for ASP, but it didn't help me much ...
我想做的是以下内容:我想创建一个用户控件,它有一个集合作为属性和按钮来浏览这个集合.我希望能够将此用户控件绑定到一个集合并在其上显示不同的控件(包含来自该集合的数据).就像您在 MS Access 中表单下边缘的内容一样......
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 ...
更准确地说:
当我在我的应用程序中实际使用控件时(在我创建它之后),我希望能够在 <myControly>
和如果我现在这样做,我的用户控件上的控件就会消失.
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.
推荐答案
以下是实现您想要的一种方式的示例:
Here is an example of one way to do what you want:
一、代码——UserControl1.xaml.cs
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); }
}
}
以及用户控件的 XAML - UserControl1.xaml
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>
最后,使用我们美妙的新控件的 xaml:
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>
这篇关于可以包含其他控件的 C# 用户控件(使用时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!