WPF 在控件上预留一个占位给到调用方使用

WPF 在控件上预留一个占位给到调用方使用,首先创建一个自定义控件,并在其中包含一个可用于承载外部内容的容器。

xml 复制代码
<!-- PlaceholderControl.xaml -->
<UserControl x:Class="YourNamespace.PlaceholderControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
         <ContentPresenter Content="{Binding PromptContent, Mode=OneWay, RelativeSource={RelativeSource AncestorType=local:PlaceholderControl}}"/>
    </Grid>
</UserControl>

在后台配置一个依赖属性PromptContent用于绑定

csharp 复制代码
        public static readonly DependencyProperty PromptContentProperty =
            DependencyProperty.Register("PromptContent", typeof(object), typeof(PlaceholderControl));
        /// <summary>
        /// Map 头部显示内容
        /// </summary>
        public object PromptContent
        {
            get { return (object)GetValue(PromptContentProperty); }
            set { SetValue(PromptContentProperty, value); }
        }

使用时,您可以将 PlaceholderControl 放置在您的 WPF 窗口或页面中,并使用 ContentPlaceholder 属性来设置外部内容。例如:

xml 复制代码
<!-- MainWindow.xaml -->
<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:PlaceholderControl>
            <local:PlaceholderControl.ContentPlaceholder>
                <!-- 这里放置您想要的外部内容 -->
                <TextBlock Text="这是外部内容"/>
            </local:PlaceholderControl.ContentPlaceholder>
        </local:PlaceholderControl>
    </Grid>
</Window>
相关推荐
zh_xuan15 分钟前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊40 分钟前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.11844 分钟前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之1 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头2 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu2 小时前
java内存模型JMM
java·开发语言
我很好我还能学4 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++
蓝婷儿4 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
渣渣盟4 小时前
基于Scala实现Flink的三种基本时间窗口操作
开发语言·flink·scala