添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
暴走的充值卡  ·  Spark ...·  2 年前    · 
新建UserControl.png
创建好控件后,就往控件中添加一些小组件了,这里就直接添加一个 TextBlock ,可以在引用控件的时候,传递 Titles 到组件中的 TextBlock 进行显示,如下所示:

<UserControl x:Class="WpfApp1.UserControl2"
             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:WpfApp1"
             DataContext="{Binding RelativeSource={RelativeSource Self}}"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
        <TextBlock x:Name="title" Text="{Binding Titles , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
    </Grid>
</UserControl>
DataContext="{Binding RelativeSource={RelativeSource Self}}"这一行一定不能少,否则传递的值无法显示,折腾了我好久。。。

2.设置属性

创建好控件好,就需要设置属性了,主要是通过DependencyProperty 来设置,设置自定义属性的代码如下所示:

public partial class UserControl2 : UserControl
        [BindableAttribute(true)]
        public string Titles
            get { return (string)GetValue(TitlesProperty); }
            set { SetValue(TitlesProperty, value); }
        public UserControl2()
            InitializeComponent();
        public static string GetTitles(DependencyObject obj)
            return (string)obj.GetValue(TitlesProperty);
        public static void SetTitles(DependencyObject obj, string value)
            obj.SetValue(TitlesProperty, value);
        public static readonly DependencyProperty TitlesProperty =
            DependencyProperty.Register("Titles", typeof(string), typeof(UserControl2), new PropertyMetadata("hhhhhh"));

3.使用组件

添加好控件及设置好属性后,就可以使用组件了,使用组件比较简单,直接拖进来或者写代码都行,如下所示:

<local:UserControl2 HorizontalAlignment="Left" Height="100" Margin="430,284,0,0" VerticalAlignment="Top" Width="100" Titles="这是自定义的组件"/>