将事件绑定到方法,为什么它可以在UWP中工作?

Aym*_*udi 6 c# data-binding xaml compiled-bindings uwp

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

范例:

Xaml:

<Grid>
    <Button Click="{x:Bind Run}" Content="{x:Bind ButtonText}"></Button>
</Grid>
Run Code Online (Sandbox Code Playgroud)

背后的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

结果 :

在此处输入图片说明

而且由于{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;
      }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Cle*_*ens 1

绑定目标应该是依赖属性

虽然这对于常规绑定来说是正确的,但对于标记扩展来说并不成立{x:Bind}

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

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

作为{x:Bind}这样的目标:

<local:MyUserControl BackgroundColor="{x:Bind ViewModel.BgColor}" />
Run Code Online (Sandbox Code Playgroud)

尽管

<local:MyUserControl BackgroundColor="{Binding ViewModel.BgColor}" />
Run Code Online (Sandbox Code Playgroud)

会失败的。