xaml部分:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Border CornerRadius="5" BorderThickness="3" BorderBrush="#FFEF410D" Width="300" Height="40" Margin="5" >
<TextBlock x:Name="txt" Text="" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>
</Border>
</UserControl>
CS部分:(技巧:vs2008中,只要鍵入propdp,再連敲二次Tab鍵,vs就會自動添加一個依賴屬性的代碼模板)
using System.Windows.Controls;
namespace DPStudy
{
public partial class MyControl : UserControl
{
public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(MyControl), new PropertyMetadata("Message的默認值", new PropertyChangedCallback(OnMessagePropertyChanged)));
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
/// <summary>
/// Message變化時的通知處理
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnMessagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyControl ctl = d as MyControl;
ctl.txt.Text = d.GetValue(MyControl.MessageProperty).ToString();
}
public MyControl()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MyControl_Loaded);
}
void MyControl_Loaded(object sender, RoutedEventArgs e)
{
this.txt.Text = Message;//初始加載時,顯示Message的初始值
}
}
}
這裏我們定義了一個Message的string類型依賴屬性,和普通屬性的區別是:必須使用DependencyProperty.Register來註冊該屬性,而且“屬性命名”要以Property爲後綴;另外在讀取時,必須調用SetValue/GetValue靜態方法來讀取其值,最後我們還可以添加一個"屬性值變化時的"回調處理。
(2)將MyControl放到MainPage.xaml中小試牛刀
MainPage.Xaml內容如下:
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:l="clr-namespace:DPStudy"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<StackPanel x:Name="LayoutRoot">
<l:MyControl x:Name="myctl"></l:MyControl>
<Button Click="Button_Click" Content="改變Message屬性值" Width="130" ></Button>
</StackPanel>
</UserControl>
MainPage.Xaml.cs內容如下:
using System.Windows.Controls;
namespace DPStudy
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
myctl.SetValue(MyControl.MessageProperty, "新值");
}
}
}
運行後,點擊按鈕將改變MyControl控件的Message屬性值,同時MyControl中的文本控件的文字也將變成"新值"
轉載請註明來自菩提樹下的楊過
出處:http://yjmyzz.cnblogs.com
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。