用户控件和自定义控件的不同点
- 在XAML中构成用户控件的样子。
- 子控件需要暴露的依赖属性有2种用途:1. 显示 2. 赋值 3. 事件。
如何暴露属性?
将2种需要暴露的依赖属性定义成用户控件的新增的自定义依赖属性。
TextBox
Text = Binding,子控件Text 用户控件被赋值,文本框变,文本框变,用户控件变。(双向绑定)。 单向绑定。 用PropertyChangedCallBack事件去实现。
方式一:单向 + 数据绑定
<UserControl
x:Class="用户控件的Name.UserControl1"
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:local="clr-namespace:用户控件的Name"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Name="uc"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<TextBlock Text="{Binding ElementName=uc, Path=Email, Mode=OneWay}" />
</UserControl>
public partial class UserControl1 : UserControl
{
public string Email
{
get { return (string)GetValue(EmailProperty); }
set { SetValue(EmailProperty, value); }
}
// Using a DependencyProperty as the backing store for Email. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EmailProperty =
DependencyProperty.Register("Email", typeof(string), typeof(UserControl1), new PropertyMetadata(""));
public UserControl1()
{
InitializeComponent();
}
}
方式二:单向 + 回调
<UserControl
x:Class="用户控件的Name.UserControl1"
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:local="clr-namespace:用户控件的Name"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Name="uc"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<TextBlock x:Name="textBlock" />
</UserControl>
public partial class UserControl1 : UserControl
{
public string Email
{
get { return (string)GetValue(EmailProperty); }
set { SetValue(EmailProperty, value); }
}
// Using a DependencyProperty as the backing store for Email. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EmailProperty =
DependencyProperty.Register(nameof(Email), typeof(string), typeof(UserControl1), new PropertyMetadata("",new PropertyChangedCallback(EmailChanged)));
private static void EmailChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uc1 = d as UserControl1;
uc1.textBlock.Text = System.Convert.ToString(e.NewValue);
}
public UserControl1()
{
InitializeComponent();
}
}
方式三:双向
如何暴露事件?
事件在VisualTree上传播,所以大部分子控件的路由事件不需要二次封装成用户控件的路由事件。路由事件可以暴露出
标签:控件,string,自定义,EmailProperty,UserControl1,用户,public,Email From: https://www.cnblogs.com/LiuwayLi/p/17773379.html