在主窗口中使用用户控件中的按钮事件

时间:2012-02-28 11:28:11

标签: wpf events user-controls

我有wpf用户控件

<StackPanel Orientation="Horizontal">
            <TextBox Name="txbInterval" Text="5"/>
            <Image Name="imgStart" Source="Images/start.png"/>
            <Image Name="imgStop" Source="Images/stop.png"/>
</StackPanel>

我在我的应用程序中多次使用此控件。此控件可以在我自己的调度程序中启动/停止执行任务。单击imgStart时,它应该使用txbInterval.Text参数创建某个任务的新实例。我在MainWindow.xaml

中有这个
<wp:TaskManager x:Name="tmToolsArMail"/>
<wp:TaskManager x:Name="tmToolsArSail"/>

我在Mainwindow.xaml.cs中需要这样的东西

tmToolsArMail_imgStart_mouseUp(...)
... new MyTask(tmToolsArMail.txbInterval.Text) ...

tmToolsArSail_imgStart_mouseUp(...)
... new MyAnotherTask(tmToolsArSail.txbInterval.Text) ...

如何?

3 个答案:

答案 0 :(得分:2)

IMO,最简单的实现方法是在UserControl上创建2 RoutedEvent(开始和停止)和1 DependencyProperty(间隔),然后在父控件(MainWindow)上订阅这些事件

答案 1 :(得分:1)

我会做的是将RoutedEvent放在用户控件中,如下所示:

    public MyUserControl()
    {
        InitializeComponent();

        imgStart.MouseUp += imgStart_MouseUp;
        imgStop.MouseUp += imgStop_MouseUp;
    }

    // Create custom routed events by first registering a RoutedEventID
    // These events use the bubbling routing strategy
    public static readonly RoutedEvent StartEvent = EventManager.RegisterRoutedEvent(
        "Start", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

    public static readonly RoutedEvent StopEvent = EventManager.RegisterRoutedEvent(
        "Stop", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

    // Provide CLR accessors for the events
    public event RoutedEventHandler Start
    {
        add { AddHandler(StartEvent, value); }
        remove { RemoveHandler(StartEvent, value); }
    }

    // Provide CLR accessors for the events
    public event RoutedEventHandler Stop
    {
        add { AddHandler(StopEvent, value); }
        remove { RemoveHandler(StopEvent, value); }
    }

    // This method raises the Start event
    void RaiseStartEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(MyUserControl.StartEvent);
        RaiseEvent(newEventArgs);
    }

    // This method raises the Stop event
    void RaiseStopEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(MyUserControl.StopEvent);
        RaiseEvent(newEventArgs);
    }

    private void imgStart_MouseUp(object sender, MouseButtonEventArgs e)
    {
        RaiseStartEvent();
    }

    private void imgStop_MouseUp(object sender, MouseButtonEventArgs e)
    {
        RaiseStopEvent();
    }

然后调用此UserControl的任何代码都可以订阅那些Start和Stop事件并执行您需要的处理。

答案 2 :(得分:1)

我喜欢实现附加命令,如果你想做一个单击样式命令 然后,您可以将它附加到稍后阶段的任何控件(它都是MVVM)。

This is a very nice article on the subject

Here is a Stack Overflow discussion that shows alternatives