C# 如何在XAML中实例化UserControl并将项添加到其容器中

C# 如何在XAML中实例化UserControl并将项添加到其容器中,c#,wpf,xaml,user-controls,C#,Wpf,Xaml,User Controls,我有以下用户控件: <UserControl x:Class="UserControlTest.UserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformat

我有以下用户控件:

<UserControl x:Class="UserControlTest.UserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel x:Name="MainPanel" Background="White">
    <TextBlock Text="BasePanel"/>
</StackPanel>
<UserControl x:Class="ucFancyMenu" x:Name="MySelf"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Label Height="30" VerticalAlignment="Top" Background="#F0F">So Fancy</Label>
        <ItemsControl Margin="0 30 0 0" ItemsSource="{Binding ElementName=MySelf, Path=Items}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</UserControl>

还有我的MainWindwo.XAML:

<Window x:Class="UserControlTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:UC="clr-namespace:UserControlTest"
    Title="MainWindow" Height="350" Width="525">
<DockPanel Name="dpMain">
    <UC:Control x:Name="ucBaseControl" />

</DockPanel>

在MainWindow.xaml.cs背后的代码中:

namespace UserControlTest
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            TextBox tbWorld = new TextBox();
            tbWorld.Text = "Hello World";
            ucBaseControl.MainPanel.Children.Add(tbWorld);
        }
    }
}
命名空间UserControlTest { /// ///Interaktionslogik für MainWindow.xaml /// 公共部分类主窗口:窗口 { 公共主窗口() { 初始化组件(); TextBox tbWorld=新建TextBox(); tbWorld.Text=“你好世界”; ucBaseControl.MainPanel.Children.Add(tbWorld); } } } 有没有办法在XAML中实现这一点以避免代码落后


提前非常感谢

您可以尝试执行以下操作:

XAML:


我是基地的
代码隐藏:

using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace WpfApplication1
{
    [ContentProperty("NewControls")]
    public partial class BaseControl : UserControl
    {
        public UIElementCollection NewControls
        {
            get { return (UIElementCollection)GetValue(NewControlsProperty); }
            set { SetValue(NewControlsProperty, value); }
        }

        public static readonly DependencyProperty NewControlsProperty = DependencyProperty.Register("NewControls", typeof(UIElementCollection), typeof(BaseControl));

        public BaseControl()
        {
            InitializeComponent();

            this.NewControls = new UIElementCollection(this, this);

            this.Loaded += BaseControl_Loaded;
        }

        void BaseControl_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (UIElement element in NewControls.Cast<UIElement>().ToList())
            {
                NewControls.Remove(element);

                this.newPanel.Children.Add(element);
            }
        }
    }
}
使用System.Linq;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Markup;
命名空间WpfApplication1
{
[内容属性(“新控件”)]
公共部分类BaseControl:UserControl
{
公共UIElementCollection控件
{
get{return(UIElementCollection)GetValue(NewControlsProperty);}
set{SetValue(NewControlsProperty,value);}
}
public static readonly dependencProperty NewControlsProperty=dependencProperty.Register(“NewControls”、typeof(UIElementCollection)、typeof(BaseControl));
公共基站控制()
{
初始化组件();
this.NewControls=newUIElementCollection(this,this);
this.Loaded+=BaseControl\u Loaded;
}
已加载void BaseControl_(对象发送器,路由目标)
{
foreach(NewControls.Cast().ToList()中的UIElement元素)
{
新建控件。删除(元素);
this.newPanel.Children.Add(元素);
}
}
}
}
在另一个控件或窗口中:

xmlns:local="clr-namespace:WpfApplication1"
...
<local:BaseControl>
    <TextBlock>I'm from new</TextBlock>
</local:BaseControl>
xmlns:local=“clr命名空间:WpfApplication1”
...
我来自纽约
不确定它是否完全符合您的需要,但可以作为一个良好的基础。

这里是我的解决方案

我的用户控件:

<UserControl x:Class="UserControlTest.UserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel x:Name="MainPanel" Background="White">
    <TextBlock Text="BasePanel"/>
</StackPanel>
<UserControl x:Class="ucFancyMenu" x:Name="MySelf"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Label Height="30" VerticalAlignment="Top" Background="#F0F">So Fancy</Label>
        <ItemsControl Margin="0 30 0 0" ItemsSource="{Binding ElementName=MySelf, Path=Items}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</UserControl>

真想不到
UserControl类:

<Markup.ContentProperty("Items")> _
Public Class ucFancyMenu

    Public Property Items As New List(Of UIElement)

End Class
_
公共类ucFancyMenu
公共财产项目作为新列表(UIElement)
末级
如何在其他XAML中使用它:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>

        <local:ucFancyMenu>
            <Button>FancyBtn 1</Button>
            <Button>FancyBtn 2</Button>
            <Button>FancyBtn 3</Button>
            <Button>FancyBtn 4</Button>
            <Button>FancyBtn 5</Button>
            <Button>FancyBtn 6</Button>
            <Button>FancyBtn 7</Button>
        </local:ucFancyMenu>

    </Grid>
</Window>

FancyBtn 1
FancyBtn 2
幻想3
幻想4
幻想5
FancyBtn 6
幻想7

Hum您有一个更大的问题:为什么主视图要对UC的内容负责?UC的目标正是将它们解耦。你到底想做什么?嘿,Pragmateek,我有两个窗口:第一个窗口就是用户控件。第二个窗口是UserControl,但有更多的UI元素。UserControl类似于我的baseWindow。因此,如果我要对UserControl进行更改,那么两个窗口都会受到诸如inheritance之类的影响,所以你需要问问自己,它们是否真的是同一种控件?答案可能仍然是肯定的,但如果这些控件有固定数量的配置(即它们将具有的内容),那么为什么不公开一个控制控件处于哪种“模式”的属性呢?然后,主窗口(或任何其他窗口)不需要向自定义控件添加UI元素,它只需要设置一个属性。这并不意味着你可以把多个元素放进去,只是把它们和你的窗口分开。在我的示例中,我创建了一个带有uniq样式和一些额外功能和属性的MenuControl。我想在几个窗口上使用这个MenuUserControl,每次都应该有divrent选项!因此,我制作了一次菜单,并在其父菜单的xaml中定义了菜单项。我将把这个解决方案作为一个普通的评论发布。你的方式很复杂。如果你想用它来让你的动作(点击按钮)离开你的菜单,而在你的窗口中你应该使用命令。