0
点赞
收藏
分享

微信扫一扫

wpf用户控件添加依赖属性

一。VS创建用户控件项目

前台界面:
在这里插入图片描述

前台代码:

<UserControl x:Class="WpfControlLibrary2.UserControl1"
             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:WpfControlLibrary2"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Height="600" Width="600" Background="Yellow">
        <Button Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:UserControl1},Path=pText}" Height="60" Margin="270,270,180,270"/>
    </Grid>
</UserControl>

后台代码:

namespace WpfControlLibrary2
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
        public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(pText), typeof(string), typeof(UserControl1), new PropertyMetadata(defaultValue: "666"));
        public string pText
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
    }
}

二.VS创建WPF应用项目

前台界面:
在这里插入图片描述

前台代码:

<Window
        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:WpfApp2"
        xmlns:wp="clr-namespace:WpfControlLibrary2;assembly=WpfControlLibrary2"
        x:Class="WpfApp2.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wp:UserControl1 pText="999"/>
    </Grid>
举报

相关推荐

0 条评论