我有一个用户控件,它有一个按钮和一个依赖属性,用于执行按钮的操作.包含该控件的页面在XAML中设置操作.
MyUserControl.cs
一个Button,以及Action类型的依赖项属性ButtonAction.单击该按钮时,它将执行ButtonAction.
MainPage.xaml.cs中
行动1
行动2
MainPage.xaml中
使用ButtonAction = Action1呈现MyUserControl的实例
问题:未从XAML分配ButtonAction属性
MyUserControl.cs
public sealed partial class MyUserControl : UserControl { public Action ButtonAction { get { return (Action)GetValue(ButtonActionProperty); } set { SetValue(ButtonActionProperty,value); } } public static readonly DependencyProperty ButtonActionProperty = DependencyProperty.Register("ButtonAction",typeof(Action),typeof(MyUserControl),new PropertyMetadata(null,ButtonAction_PropertyChanged)); private static void ButtonAction_PropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { Debug.WriteLine("ButtonAction_PropertyChanged"); // Is not called! } public MyUserControl() { this.InitializeComponent(); } private void Button_Click(object sender,RoutedEventArgs e) { if (ButtonAction != null) { // Never reaches here! ButtonAction(); } } }
MyUserControl.xaml
<Grid> <Button Click="Button_Click">Do The Attached Action!</Button> </Grid>
MainPage.xaml.cs中
Action Action1 = ( () => { Debug.WriteLine("Action1 called"); }); Action Action2 = (() => { Debug.WriteLine("Action2 called"); });
MainPage.xaml中
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <local:MyUserControl x:Name="myUserControl" ButtonAction="{Binding Action1}"/> </Grid>
如果在MainPage(MainPage.xaml.cs)的代码隐藏中,我在Loaded事件中分配操作,它确实有效.
private void Page_Loaded(object sender,RoutedEventArgs e) { this.myUserControl.ButtonAction = Action1; }
在这种情况下,还会调用用户控件中的PropertyChanged回调. (此处理程序仅用于诊断目的.我无法在实践中看到它如何用于支持该属性).
问题出在您的数据绑定中. ButtonAction =“{Binding Action1}”中的Action1应该是公共属性,而您将其定义为私有变量.
此外,您不能直接在后面的代码中声明一个普通的属性.您将需要一个依赖项属性,或更常见的是一个实现INotifyPropertyChanged的viewmodel中的公共属性.
如果我们采用第二种方法,我们需要使用Action1属性创建一个类似于以下的viewmodel类.注意OnPropertyChanged的东西只是实现INotifyPropertyChanged的标准方法.
public class viewmodel : INotifyPropertyChanged { private Action _action1; public Action Action1 { get { return _action1; } set { _action1 = value; OnPropertyChanged("Action1"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { var handler = PropertyChanged; if (handler != null) { handler(this,new PropertyChangedEventArgs(name)); } } }
然后你只需要将它分配给主页面的DataContext.
public MainPage() { this.InitializeComponent(); var vm = new viewmodel(); vm.Action1 = (() => { Debug.WriteLine("Action1 called"); }); this.DataContext = vm; }
通过这两个更改,您的ButtonAction回调应该立即触发. 原文链接:https://www.f2er.com/windows/441490.html