做界面身害,要想快味悄,就得學(xué)會(huì)封裝控件,對于一些比較常用的控件塌鸯,封裝成公用的控件侍瑟,可以提升開發(fā)效率。在開發(fā)前丙猬,可以先看下設(shè)計(jì)稿涨颜,對于一些常用的樣式费韭,可以封裝成一個(gè)控件,比如說我們經(jīng)常會(huì)碰到一種這樣的樣式咐低,左邊顯示標(biāo)題揽思,右邊顯示內(nèi)容,一般需要兩個(gè)TextBlock
见擦,為了便于以后修改樣式钉汗,可以封裝在一個(gè)UserControl
中。下面就來看一下在WPF
中怎么封裝控件的鲤屡,以及封裝時(shí)需要注意什么损痰。
1.新建UserControl
首先需要新建一個(gè)UserControl
,如下所示:
新建UserControl.png
創(chuàng)建好控件后酒来,就往控件中添加一些小組件了卢未,這里就直接添加一個(gè)
TextBlock
,可以在引用控件的時(shí)候堰汉,傳遞Titles
到組件中的TextBlock
進(jìn)行顯示辽社,如下所示:
<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">
<Grid>
<TextBlock x:Name="title" Text="{Binding Titles , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</Grid>
</UserControl>
- 坑
DataContext="{Binding RelativeSource={RelativeSource Self}}"
這一行一定不能少,否則傳遞的值無法顯示翘鸭,折騰了我好久滴铅。。就乓。
2.設(shè)置屬性
創(chuàng)建好控件好汉匙,就需要設(shè)置屬性了,主要是通過DependencyProperty 來設(shè)置生蚁,設(shè)置自定義屬性的代碼如下所示:
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.使用組件
添加好控件及設(shè)置好屬性后噩翠,就可以使用組件了,使用組件比較簡單邦投,直接拖進(jìn)來或者寫代碼都行伤锚,如下所示:
<local:UserControl2 HorizontalAlignment="Left" Height="100" Margin="430,284,0,0" VerticalAlignment="Top" Width="100" Titles="這是自定義的組件"/>
自定義組件.png
UserControl2
為創(chuàng)建的組件類。Titles="這是自定義的組件"
為自定義屬性傳值志衣。好了见芹,一個(gè)簡單的組件就這么完成了。
個(gè)人博客