【发布时间】:2012-12-03 06:27:16
【问题描述】:
我正在寻找以下情况的解决方案。
在我的应用程序中,我有一个名为 page1 的页面,并且我在 page1 中放置了一个用户控件。我的要求是我需要在 page1 的代码后面获取用户控件中使用的按钮的单击事件。我如何在 windows phone / silverlight 中实现同样的效果。
【问题讨论】:
标签: windows-phone-7 silverlight-4.0
我正在寻找以下情况的解决方案。
在我的应用程序中,我有一个名为 page1 的页面,并且我在 page1 中放置了一个用户控件。我的要求是我需要在 page1 的代码后面获取用户控件中使用的按钮的单击事件。我如何在 windows phone / silverlight 中实现同样的效果。
【问题讨论】:
标签: windows-phone-7 silverlight-4.0
(如果您知道 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 中。
就像您公开MyControlButtonClickCommand 依赖属性一样,您可以公开一个事件MyControlButtonClick 并在页面的xaml 中订阅它,而不是公开它。在您的 UserControl 代码内部,您应该订阅它的按钮的 Click 事件并触发它自己的 MyControlButtonClick 事件。
希望这会对你有所帮助。
【讨论】:
<namespace:MyControl ../> 如何将 viewModel 命令绑定到 usercontrol 的 buttonclick?请帮助 wpf windows phone 新手...
有两种方法, 最简单的方法是双击演示布局上的按钮。
或者
在 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
}
【讨论】:
对于 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!!
}
}
【讨论】: