一。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">
<Button Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:UserControl1},Path=pText}" Height="60" Margin="270,270,180,270"/>
</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>
三.demo下载地址
https://download.csdn.net/download/sdfjasad/81152587