WPF - 在 UserControl 中托管内容

标签 wpf user-controls

我正在尝试创建一个具有两行Grid 的用户控件。 第一行表示标题,第二行表示将在用户控件外部定义的内容,例如我们示例中的 Button

不知何故,我没有让它发挥作用。

UserControl1 xaml:

  <Grid Background="LightBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
</Grid>

主窗口xaml:

 <Grid>
    <local:UserControl1>
        <Button>Click me</Button>
    </local:UserControl1>
</Grid>

下面的图片应该可以解释我的问题: enter image description here

最佳答案

以下代码

<local:UserControl1>
    <Button>Click me</Button>
</local:UserControl1>

意味着您将UserControl1 的Content 属性设置为该按钮。此按钮仅替换 UserControls1 的标记。因此,UserControl1.xaml 中的所有内容都不再存在。

编辑

如果您希望 UserControl 托管一些将在其外部某处设置的标记,您可以向其添加 DependencyProperty,例如:

    /// <summary>
    /// Gets or sets additional content for the UserControl
    /// </summary>
    public object AdditionalContent
    {
        get { return (object)GetValue(AdditionalContentProperty); }
        set { SetValue(AdditionalContentProperty, value); }
    }
    public static readonly DependencyProperty AdditionalContentProperty =
        DependencyProperty.Register("AdditionalContent", typeof(object), typeof(UserControl1),
          new PropertyMetadata(null));

并向其标记添加一些元素以托管附加内容。以下是扩展您提供的标记的示例:

<UserControl ... Name="userControl">
    <Grid Background="LightBlue">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
        <ContentPresenter Content="{Binding AdditionalContent, ElementName=userControl}" />
    </Grid>
</UserControl>

现在您可以按如下方式使用它:

<local:UserControl1>
    <local:UserControl1.AdditionalContent>
        <Button>Click me</Button>
    </local:UserControl1.AdditionalContent>
</local:UserControl1>

关于WPF - 在 UserControl 中托管内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427133/

相关文章:

.net - 缩放整个 WPF 窗口

wpf StringFormat 问题

c# - 如何创建一个可以在其中放置其他控件的 UserControl?

asp.net - 用户控件事件不会在 Httphandler 中触发

python - save_model 方法,但数据库需要不同的关系?

wpf - 有没有像 WPF ListView 这样没有选择的东西?

c# - 如何将 CommandParameter 与 RelayCommand 一起使用?

使用拖动矩形的 WPF 形状多重选择

wpf - 如何为自定义用户控件按钮连接单击事件?我应该使用自定义控件吗?

c# - .net 对象资源管理器控件