繁体   English   中英

将事件绑定到方法,为什么它在UWP中有效?

[英]Binding an event to a method, why does it work in UWP?

UWP带来了一种新的DataBindingCompiled Binding ,使用{x:Bind}标记扩展,当我发现这个新功能时,我发现我们实际上可以将一个事件绑定到一个方法!

示例:

Xaml:

<Grid>
    <Button Click="{x:Bind Run}" Content="{x:Bind ButtonText}"></Button>
</Grid>

代码背后:

private string _buttonText;

public string ButtonText
{
     get { return _buttonText; }
     set
         {
             _buttonText = value;
             OnPropertyChanged();
         }
}

public MainPage()
{
    this.InitializeComponent();
    ButtonText = "Click !";
}

public async void Run()
{
    await new MessageDialog("Yeah the binding worked !!").ShowAsync();
}

结果 :

在此输入图像描述

并且由于{x:Bind}绑定在运行时被评估,并且编译器生成了一些表示该绑定的文件,所以我去那里调查发生了什么,所以在MainPage.g.cs文件中(MainPage是有问题的xaml文件) ) 我找到了这个 :

 // IComponentConnector

 public void Connect(int connectionId, global::System.Object target)
 {
      switch(connectionId)
      {
           case 2:
           this.obj2 = (global::Windows.UI.Xaml.Controls.Button)target;
                        ((global::Windows.UI.Xaml.Controls.Button)target).Click += (global::System.Object param0, global::Windows.UI.Xaml.RoutedEventArgs param1) =>
           {
               this.dataRoot.Run();
           };
                break;
           default:
                break;
      }
}

编译器似乎知道它是一个有效的绑定,而且它创建了相应的事件处理程序,并在内部调用相关的方法。

太棒了 ! 但为什么 ?? 绑定目标应该是依赖属性,而不是事件。 {x:Bind}的官方文档确实提到了这个新功能,但没有解释为什么以及如何将非依赖属性作为绑定目标,任何对此有深刻解释的人?

嗯,这是“x:Bind”编译绑定的新功能。

https://msdn.microsoft.com/en-us/library/windows/apps/mt204783.aspx

事件绑定是编译绑定的新功能。 它使您能够使用绑定指定事件的处理程序,而不必在后面的代码上指定方法。 例如:Click =“{x:Bind rootFrame.GoForward}”。

对于事件,目标方法不得重载,还必须:

  1. 匹配事件的签名。
  2. 或没有参数。
  3. 或者具有相同数量的可从事件参数类型分配的类型参数。

我猜你的场景完全符合第2项。

绑定目标应该是依赖属性

虽然这对于常规绑定是正确的,但它不适用于{x:Bind}标记扩展。

所以你实际上可以有一个非依赖属性,例如

public sealed partial class MyUserControl : UserControl
{
    public Color BackgroundColor
    {
        get { return ((SolidColorBrush)Background).Color; }
        set { Background = new SolidColorBrush(value); }
    }
}

像这样的{x:Bind}目标:

<local:MyUserControl BackgroundColor="{x:Bind ViewModel.BgColor}" />

<local:MyUserControl BackgroundColor="{Binding ViewModel.BgColor}" />

会失败的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM