【WPF】Xaml用户控件(Usercontrol)绑定属性/事件
程序员文章站
2022-03-04 11:49:08
...
Usercontrol可以将已有的控件重新组合为新的控件,本文将会说明如何实现前台代码设置Usercontol的属性以及事件。
首先,我们先新建一个Usercontrol,命名为:UC
UC中,有一个Label和一个Button。
UC的 LabelText 属性与 Label 的 Content 绑定在一起。
UC的BTNClick属性与Button的Click事件关联在一起。
xaml代码:
<Grid >
<Label Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UC}}, Path=LabelText}"/>
<Button Content="Button"
HorizontalAlignment="Left"
Margin="85,102,0,0" VerticalAlignment="Top"
Width="75"
Click="Button_Click"/>
</Grid>
cs代码:
public partial class UC : UserControl
{
public UC()
{
InitializeComponent();
}
#region Label
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("LabelText", typeof(string), typeof(UC));
public string LabelText
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
#endregion
#region Button
public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("BTNClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UC));
public event RoutedEventHandler BTNClick
{
add { AddHandler(ClickEvent, value); }
remove { RemoveHandler(ClickEvent, value); }
}
void RaiseSelectedEvent()
{
var arg = new RoutedEventArgs(ClickEvent);
RaiseEvent(arg);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
RaiseSelectedEvent();
}
#endregion
}
特别提示:
如果使用控件时,Xaml代码报错了,可以先尝试直接启动程序。如果程序能启动,就是代码没问题了。
如果代码没问题[ 重启VS ]!!就能正常显示了。