我需要将 UI 元素的位置保存到变量中。我将 x
和 y
放入我的集合并绑定(bind)它
<Canvas>
<Grid
Canvas.Top="{x:Bind PositionY, Mode=TwoWay}"
Canvas.Left="{x:Bind PositionX, Mode=TwoWay}"
还有我的“模特”
public double PositionX {get;set;}
public double PositionY {get;set;}
然后我通过移动在页面上更改它并尝试在集合中更新它们
但是如果我设置 Mode=TwoWay
我有编译错误
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 的版本时,它会生成如下代码来更新双向绑定(bind):
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
,它不包含名为 Left
或 Top
的属性,所以我们会得到编译器错误。
要解决此问题,应用的最低目标 SDK 版本必须为 14393 或更高版本。要更改已在 Visual Studio 中创建的项目的最低版本和目标版本,请转至项目 → 属性 → 应用程序选项卡 → 目标。
在此之后,我们可以Rebuild 工程,这样应该不会出现编译错误。应该正确生成绑定(bind)。
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);
}
});
关于c# - 无法将 TwoWay 模式设置为 x :Bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060398/