WPF:如何在自定义控件中使用事件 [英] WPF : How to Use Event in Custom Control

查看:200
本文介绍了WPF:如何在自定义控件中使用事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



看起来我有基本接口
这是自定义控件库
我想按下一个带有事件的按钮
并将此按钮及其事件继承到另一个接口

像这样:::
在代码Generic.xaml

hi ,

look i have a base interface
which is custom control library
and i want to put a button with an event
and inherit this button with his event to another interfaces

like this:::
in code Generic.xaml

<br />
<br />
<br />
<pre lang="xml"><ResourceDictionary<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:local="clr-namespace:Base_Dialog"<br />
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"><br />
    <Style TargetType="{x:Type local:BaseDlg}" ><br />
        <Setter Property="Template"><br />
            <Setter.Value><br />
                <ControlTemplate TargetType="{x:Type local:BaseDlg}" ><br />
                    <Grid Background="Red"><br />
                        <Grid.RowDefinitions><br />
                            <RowDefinition Height="Auto"/><br />
                            <RowDefinition Height="Auto"/><br />
                        </Grid.RowDefinitions><br />
                        <ContentPresenter x:Name="windowContent" Content="{TemplateBinding Property=ContentControl.Content}" Margin="4" Grid.Row="0"/><br />
                        <Button Content="enas"  Click="New_Event" Height="20" Width="20" Grid.Row="1"/><br />
                    </Grid><br />
                </ControlTemplate><br />
            </Setter.Value><br />
        </Setter><br />
    </Style><br />
</ResourceDictionary></pre>





多数民众赞成表示第一个界面将是
基本界面
而另一个
将会是孩子们

我想邀请代码事件((New_Event))..我在哪里放置代码,


我希望尽快回答





thats mean the first intrface will be the
base interface
and the other
will be ts childs

And I want to guest code event((New_Event)) .. Where do I put the code,


I hope to answer as soon as possible

推荐答案

形式上,该事件可以是任何委托类型.但是,建议对事件进行特殊约束:建议使用委托类型System.EventHandler或通用委托类型EventHandler<TEventArgs>(其中TEventArgsSystem.EventArgs)声明事件.由于许多原因,最好遵循此建议.例如FxCop( http://en.wikipedia.org/wiki/FxCop [
Formally, the event can be of any delegate type. However, there is a special constraint for event considered as a recommended practice: the event should declared using the delegate type System.EventHandler or generic delegate type EventHandler<TEventArgs> where TEventArgs is System.EventArgs. By many reasons, it''s best to follow this recommendation. For example FxCop (http://en.wikipedia.org/wiki/FxCop[^]) will require following this Microsoft rule by default.

That said, you can declare your event using non-generic System.EventHandler is you don''t have any custom data to be passed to the even when you fire it. In this case you need to pass sender (which is the normally is same instance of the class which fires the event) and an instance of System.EvenArgs which does not carry any usual information. For example, your class (such as User Control) can declare even Click which only carry information on what is clicked, without any information on what''s clicked (mouse coordinate, keyboard state, control state or anything else):

class MyControl {
    public event EventHandler Click;
    void FireClick() {
         if (Click != null)
             Click(this, new System.EventArgs());
    }
}



要传递任意数量的自定义参数,您应该使用EventHander的通用版本.事件的声明需要两个步骤.首先,您需要为通用参数创建一个类型.根据通用类型参数约束,它应该是从System.EvenArgs派生的类,例如:



To pass any number of custom parameters you should use generic version of EventHander. The declaration of event needs two steps. First, you need to create a type for generic parameter. According to generic type parameter constraint, it should be a class derived from System.EvenArgs, for example:

[System.Flags]
public enum MyControlStates = { None, /*...*/ }
public class MyCustomEventArgs : System.EventArgs {
    //should not be public,
    //because you only fire your event from the class in the same assembly:
    internal MyCustomEventArgs(MyControlStates stated, System.Drawing.Point mouseCoordinates) {
        //...
    } 
    public System.Drawing.Point MouseCoordinates { get { /*...*/ } }
    public MyControlStates MyControlStates { get { /*...*/ } }
}



现在您可以声明事件本身:



Now you can declare the event itself:

class MyControl {
    public event EventHandler<MyCustomEventArgs> StateChanged;
    void FireStateChanged() {
         if (StateChanged != null)
             StateChanged(this, new MyCustomEventArgs(/*...*/));
    }
}



您没有询问有关设置事件处理程序的问题,但是我建议在所有情况下都使用匿名委托.对于C#v.3或更高版本(您正在使用v.4),最好的形式是lambda:



You did not ask about setting event handlers, but I recommend to use anonymous delegates in all cases; and for C# v.3 or later (you''re using v.4) the best form of it is lambda:

MyControlInstance.StateChanges += (sender, eventArgs) => {
    //do something depending on eventArgs.MouseCoordinates or
    //eventArgs.MyControlStates (see above)
};



这是最方便的,因为您不必为每个事件都使用具有完全相同参数的单独方法(通常不使用某些参数,为什么要重现它们),您甚至可以立即在匿名方法(我建议仅在简单情况下使用).此外,使用lambda时,甚至不需要类型名称:从事件类型(类型推断)推断类型.

查看更多有关使用事件的信息:
如何调用keydown单击特定按钮上的事件 [ ^ ].

—SA



This is the most convenient, because you don''t have to have a separate method for every event with strictly the same parameters (some of parameters are often not used, why reproduce them), you can even write all the code immediately in the anonymous method (I recommend it only in simple cases). Moreover, with lambda even type name are not needed: types are inferred from the event type (type inference).

See more on using events: how to call keydown event on particular button click[^].

—SA


这篇关于WPF:如何在自定义控件中使用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆