这看起来确实是一件简单的事情,但我无法弄清楚。
我不使用 xaml、纯 C# 标记来创建视图。 我有一个
DataTemplate
,我可以轻松地将视图绑定到并使用 C# 标记在后面形成 ViewModel 代码。但现在我宁愿将一个 View
直接绑定到另一个 View
。我能找到的唯一示例是在 xaml 中,如此视频中所做的那样
所以看起来就这么简单,这当然行不通,因为我怀疑
Label
Binding
不知道通往Border
的路径是什么
internal class BinaryItemDataTemplate : DataTemplate
{
internal BinaryItemDataTemplate()
{
LoadTemplate = static () =>
{
Label label = new() { Text = "unset" };
var border = new Border();
label.SetBinding(Label.TextProperty, nameof(border.IsFocused)); // whats the path/source
return border;
};
}
}
正如我所说,我可以简单地做到这一点并将
Border
绑定到 ViewModel
border.SetBinding(Border.IsFocusedProperty, nameof(BinaryItem.IsFocused), BindingMode.TwoWay);
并将其绑定回
Label
selectedLabel.SetBinding(Label.TextProperty, nameof(BinaryItem.IsFocused));
但我想直接这样做,因为可以用所有 xaml 废话来完成。
似乎您想在代码隐藏中使用
x:Reference
绑定。但是,x:Reference
是 XAML 构造,在 C# 代码中不可用。
作为替代方案,您可以自定义自己的绑定。
LoadTemplate = static () =>
{
Label label = new() { Text = "unset" };
var border = new Border();
// use the following line to bind the label's Text property
// to the IsFocused Property of border
label.SetBinding(Label.TextProperty, new Binding(source:border ,path:"IsFocused"));
return border;
};
更多信息可以参考 BindableObject.SetBinding(BindableProperty, BindingBase) 方法。
希望有帮助!