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
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。