wpf自定義控件中使用自定義事件
阿新 • • 發佈:2017-08-29
object reg on() padding mman dex bubble 名稱 binding
wpf自定義控件中使用自定義事件
1 創建自定義控件及自定義事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/// <summary>
/// 演示用的自定義控件
/// </summary>
public class ExtButton : Button
{
public ExtButton()
{
base .Click += ExtButton_Click; }
private void ExtButton_Click( object sender, RoutedEventArgs e)
{
//定義傳遞參數
// RoutedPropertyChangedEventArgs<Object> args = new RoutedPropertyChangedEventArgs<Object>("1", "2", ControlLoadOverEvent);
RoutedEventArgs args2 = new RoutedEventArgs(ControlLoadOverEvent, this );
//引用自定義路由事件
this .RaiseEvent(args2);
}
/// <summary>
/// 聲明路由事件
/// 參數:要註冊的路由事件名稱,路由事件的路由策略,事件處理程序的委托類型(可自定義),路由事件的所有者類類型
/// </summary>
public static readonly RoutedEvent ControlLoadOverEvent = EventManager.RegisterRoutedEvent( "ControlLoadOverEvent" , RoutingStrategy.Bubble, typeof (RoutedPropertyChangedEventArgs<Object>), typeof (ExtButton));
/// <summary>
/// 處理各種路由事件的方法
/// </summary>
public event RoutedEventHandler ControlLoadOver
{
//將路由事件添加路由事件處理程序
add { AddHandler(ControlLoadOverEvent, value); }
//從路由事件處理程序中移除路由事件
remove { RemoveHandler(ControlLoadOverEvent, value); }
}
}
|
2 使用並綁定自定義控件的事件
1 2 3 4 5 6 7 8 |
<!--i為System.Windows.Interactivity引用-->
<ext:ExtButton x:Name= "extButton" Content= "綁定自定義事件" HorizontalAlignment= "Left" Margin= "123,10,0,0" VerticalAlignment= "Top" Width= "95" >
<i:Interaction.Triggers>
<i:EventTrigger EventName= "ControlLoadOver" >
<i:InvokeCommandAction Command= "{Binding ButtonLoadOverCommand}" CommandParameter= "{Binding ElementName=extButton}" ></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ext:ExtButton>
|
3 觸發自定義事件後的操作
方式1
1 2 3 4 5 6 7 8 9 10 |
public DelegateCommand<Object> ButtonLoadOverCommand { get ; set ; }
public void ButtonLoadOver(Object obj)
{
//這裏的參數為自定義控件對象
ExtButton btn = obj as ExtButton;
if (btn != null )
{
var content = btn.Content;
}
}
|
方式2
1 2 3 4 5 6 7 |
this .extButton.ControlLoadOver += ExtButton_ControlLoadOver;
private void ExtButton_ControlLoadOver( object sender, RoutedEventArgs e)
{
var btn = (Button)e.Source;
var str = btn.Content;
}
|
wpf自定義控件中使用自定義事件