如何在 C# 标记中将一个视图直接绑定到另一个视图(没有 xaml,没有 ViewModel/代码隐藏)

问题描述 投票:0回答:1

这看起来确实是一件简单的事情,但我无法弄清楚。

我不使用 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 废话来完成。

data-binding maui
1个回答
0
投票

似乎您想在代码隐藏中使用

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) 方法

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.