在其保留页面的代码中处理用户控件的事件

时间:2012-12-03 06:27:16

标签: windows-phone-7 silverlight-4.0

我正在寻找以下情况的解决方案。

在我的应用程序中,我有一个页面说page1,我在page1中放置了一个用户控件。我的要求是我需要在page1的代码后面的用户控件中使用按钮的click事件。我如何在windows phone / silverlight中实现同样的目标。

3 个答案:

答案 0 :(得分:14)

1。第一种和正确的方式:

(如果您了解MVVM模式)将由您控制,例如MyControl,以公开类型为ICommand的DependencyProperty,例如, MyControlButtonClickCommand。

的Xaml:

<UserControl>
    <Button Command={Binding MyControlButtonClickCommand, Source={RelativeSource Self}} />
</UserControl>  

代码隐藏:

public ICommand MyControlButtonClickCommand
{
    get { return (ICommand)GetValue(MyControlButtonClickCommandProperty); }
    set { SetValue(MyControlButtonClickCommandProperty, value); }
}

public static readonly DependencyProperty MyControlButtonClickCommandProperty =
        DependencyProperty.Register("MyControlButtonClickCommand", typeof(ICommand), typeof(MyControl), new PropertyMetadata(null));  

您可以按如下方式使用UserControl:

<phone:PhoneApplicationPage>

    <namespace:MyControl MyControlButtonClickCommand="{Binding ControlButtonCommand}" />

</phone:PhoneApplicationPage>

ControlButtonCommand是ViewModel(您的自定义对象)的属性,位于Page的DataContext中。

2。还有一种更简单,更肮脏的方式,我不鼓励你去:

就像你公开MyControlButtonClickCommand依赖属性而不是暴露它一样,你可以公开一个事件MyControlButtonClick并在页面的xaml订阅它。在UserControl的代码内部,您应该订阅它的按钮的Click事件并触发其自己的MyControlButtonClick事件。

希望这会对你有所帮助。

答案 1 :(得分:1)

有两种方法可以做到, 最简单的是双击演示文稿布局上的按钮。

或者

在XML中添加onCLick = 这样做会弹出菜单以选择新事件。点击它,你点击按钮的事件应该在后面的代码上。

<button name="b1" onClick="button1_Click()"/> <!--this is what ur XAML will look like -->

处理按钮点击

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Handle the click event here

}

答案 2 :(得分:0)

对于UserControl,您可以创建一个Page1.xaml.cs将实现的接口。

public partial Class SomeControl : UserControl
{
    private OnButtonClick button_click;

    public interface OnButtonClick
    {
        void someMethod();   // generic, you can also use parameters to pass objects!!
    }

    // Used to add interface to dynamic controls
    public void addButtonClickInterface(OnButtonClick button_click)
    {
        this.button_click = button_click;
    }

    // Buttons UserControlled Click
    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        if(button_click != null)
        {
            button_click.someMethod();  
        }
    }

}

以下是如何实施和使用它。

public partial class Page1 : PhoneApplicationPage, SomeControl.OnButtonClick
{

    public Page1()
    {
        InitializeComponent()

        // for a new Control
        SomeControl cntrl = new SomeControl();
        cntrl.addButtonClickInterface(this);

        // or for a control in your xaml
        someControl.addButtonClickInterface(this);
    }

    public void someMethod()
    {
        // Here is where your button will trigger!!
    }

}
相关问题