首页 > 解决方案 > 如何更改 ContentControl 中的 Content 属性

问题描述

我有自定义 ContentControl

public class MyContentControl: ContentControl
{....}

像这样在 XAML 中定义的内容

    <controls:MyContentControl x:Name="myContentControl">
        <controls:MyContentControl.Content>
            <controls:UserControl1 />
        </controls:MyContentControl.Content>
    </controls:MyContentControl>

当我启动我的应用程序时,内容会显示在设计器和设备中。但是当我尝试以编程方式更改 Content 属性时,例如

        UserControl2 control2 = new UserControl2();            
        myContentControl.Content = control2;

MyContentControl 什么也不显示。使用标准 ContentControl 给出相同的结果。欢迎任何建议。

标签: c#xamluwpuwp-xaml

解决方案


我按照您的代码制作了简单的代码示例进行测试。这里没有问题。

public class CustomContentControl:ContentControl
{//......}

<Grid>
    <local:CustomContentControl x:Name="content">
    </local:CustomContentControl>
</Grid>
MyUserControl1 myUserControl1 = new MyUserControl1();
content.Content = myUserControl1;
<UserControl
x:Class="AppContent.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppContent"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <TextBox Text="abc"></TextBox>
</Grid>

您可能已经在代码中进行了一些特定设置。@Martin Zikmund 的建议也是合理的。您可以参考他的建议并检查您的代码。之后,如果您仍然不能解决这个问题,请提供一个Minimal, Complete, and Verifiable example

在此处输入图像描述


推荐阅读