How to bind a View directly to another View, in c# markup (no xaml, no ViewModel/codebehind)

48 Views Asked by At

This really seems like a simple thing but i cant figure it out.

Im not using xaml, pure c# markup to create views. I have a DataTemplate and I can easily bind Views to and form a ViewModel code behind using c# markup. But now Id rather bind a View directly to another View. The only examples i can find of this are in the xaml as is done in this video

So it seems as simple as this, which of course does not work as i suspect that Label Binding has no idea what the path to the Border is

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;
        };
    }
}

As i stated I can simple do this and bind the Border to the ViewModel

border.SetBinding(Border.IsFocusedProperty, nameof(BinaryItem.IsFocused), BindingMode.TwoWay);

And bind that back to the Label

selectedLabel.SetBinding(Label.TextProperty, nameof(BinaryItem.IsFocused));

But Id like to do it directly as can be done with all that xaml nonsense.

1

There are 1 best solutions below

1
Liqun Shen-MSFT On BEST ANSWER

Seems that you want to use x:Reference binding in code behind. However, x:Reference is a XAML construct and it's not available in C# code.

As an alternative, you could customize your own bindings.

    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;
    };

For more info, you could refer to BindableObject.SetBinding(BindableProperty, BindingBase) Method.

Hope it helps!