我期待为以下情况的解决方案。
在我的应用我有一个页面说第1页和我放在第1页中的用户控件。 我的要求是我需要得到用户的控制使用的第一页上的代码背后的按钮的单击事件。 我如何能实现的windows phone / Silverlight的相同。
我期待为以下情况的解决方案。
在我的应用我有一个页面说第1页和我放在第1页中的用户控件。 我的要求是我需要得到用户的控制使用的第一页上的代码背后的按钮的单击事件。 我如何能实现的windows phone / Silverlight的相同。
(如果你知道MVVM模式)将是你控制的,说MyControl
,暴露类型的DependencyProperty ICommand
,故名如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));
你会用你用户控件如下:
<phone:PhoneApplicationPage>
<namespace:MyControl MyControlButtonClickCommand="{Binding ControlButtonCommand}" />
</phone:PhoneApplicationPage>
凡ControlButtonCommand
是一个视图模型(自定义对象)的属性,住在你的DataContext的Page
。
就像你暴露MyControlButtonClickCommand
依赖属性和,而不是揭露它,你可以公开事件MyControlButtonClick
,并在页面的XAML订阅。 内部在用户控件的代码,您应该订阅它的按钮的Click
事件,并触发其自身MyControlButtonClick
事件。
希望这会帮助你。
有两种方法可以做到这一点,最简单的是双击上呈现布局的按钮。
要么
在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
}
对于用户控件,你可以创建你的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!!
}
}