无法将 TwoWay 模式设置为 x:Bind

Cannot set TwoWay mode to x:Bind

我需要将 UI 元素的位置保存到变量中。我将 xy 放入我的 collection 并绑定它

  <Canvas>
   <Grid
     Canvas.Top="{x:Bind PositionY, Mode=TwoWay}"
     Canvas.Left="{x:Bind PositionX, Mode=TwoWay}"

还有我的'model'

public double PositionX {get;set;}
public double PositionY {get;set;}

然后我通过移动在页面上更改它并尝试在 collection 中更新这些 但是如果我设置 Mode=TwoWay 我有 compile error

Severity Code Description Project File Line Suppression State Error CS1061 'Grid' does not contain a definition for 'Top' and no extension method 'Top' accepting a first argument of type 'Grid' could be found

这是一个编译器问题,已在 Windows 10 周年更新 SDK (14393) 中修复。

众所周知,{x:Bind} 使用生成的代码来实现其优势。在 XAML 编译时,{x:Bind} 被转换为将从数据源上的 属性 获取值的代码,并将其设置在标记中指定的 属性 上。

当应用程序针对早于 14393 的版本时,它会生成如下代码来更新双向绑定:

this.obj2 = (global::Windows.UI.Xaml.Controls.Grid)target;
(this.obj2).RegisterPropertyChangedCallback(global::Windows.UI.Xaml.Controls.Canvas.LeftProperty,
    (global::Windows.UI.Xaml.DependencyObject sender, global::Windows.UI.Xaml.DependencyProperty prop) =>
    {
        if (this.initialized)
        {
            // Update Two Way binding
            this.dataRoot.PositionX = (this.obj2).Left;
        }
    });
(this.obj2).RegisterPropertyChangedCallback(global::Windows.UI.Xaml.Controls.Canvas.TopProperty,
    (global::Windows.UI.Xaml.DependencyObject sender, global::Windows.UI.Xaml.DependencyProperty prop) =>
    {
        if (this.initialized)
        {
            // Update Two Way binding
            this.dataRoot.PositionY = (this.obj2).Top;
        }
    });

obj2 是一个 Grid,它不包含一个叫做 LeftTop 的 属性,所以我们会得到编译器错误。

要解决此问题,应用的最低目标 SDK 版本必须为 14393 或更高版本。要更改已在 Visual Studio 中创建的项目的最低版本和目标版本,请转至 项目 → 属性 → 应用程序选项卡 → 目标

在此之后,我们可以重建项目,那么应该不会出现编译错误。应该正确生成绑定。

this.obj2 = (global::Windows.UI.Xaml.Controls.Grid)target;
(this.obj2).RegisterPropertyChangedCallback(global::Windows.UI.Xaml.Controls.Canvas.LeftProperty,
    (global::Windows.UI.Xaml.DependencyObject sender, global::Windows.UI.Xaml.DependencyProperty prop) =>
    {
        if (this.initialized)
        {
            // Update Two Way binding
            this.dataRoot.PositionX = global::Windows.UI.Xaml.Controls.Canvas.GetLeft(this.obj2);
        }
    });
(this.obj2).RegisterPropertyChangedCallback(global::Windows.UI.Xaml.Controls.Canvas.TopProperty,
    (global::Windows.UI.Xaml.DependencyObject sender, global::Windows.UI.Xaml.DependencyProperty prop) =>
    {
        if (this.initialized)
        {
            // Update Two Way binding
            this.dataRoot.PositionY = global::Windows.UI.Xaml.Controls.Canvas.GetTop(this.obj2);
        }
    });