用户控件为什么显示不出文本?

tonylll 2025-06-30 22:20:39

我创建了一个控件uc,里面有一个依赖属性MyText,但是我在主界面里对MyText赋值了,就是显示不出来

1.uc.xaml的代码:

<UserControl x:Class="Test.uc"
             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" 
             xmlns:local="clr-namespace:Test"
             mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="200">
    <Grid>
        <ContentControl Content="{Binding MyText}"/>
    </Grid>
</UserControl>

2.uc.xaml.cs的代码:

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace Test
{
    public partial class uc : UserControl
    {
        public static readonly DependencyProperty MyTextProperty =
            DependencyProperty.Register("MyText", typeof(string), typeof(uc), new PropertyMetadata(""));

        [Bindable(true)]
        public string MyText
        {
            get { return (string)GetValue(MyTextProperty); }
            set { SetValue(MyTextProperty, value); }
        }

        public uc()
        {
            InitializeComponent();
        }
    }
}

3.MainWindow.xaml的代码:

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        mc:Ignorable="d" Title="MainWindow" Height="100" Width="200">
    <Grid>
        <local:uc MyText="hello"/>
    </Grid>
</Window>

4.MainWindow.xaml.cs的代码:

using System.Windows;

namespace Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

 

我想要的效果是主界面显示"hello"文本,但是主界面一片空白,是怎么回事,谢谢!

 

而且public string MyText的get,set都没有被触发过

...全文
16 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

8,756

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧