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
}