x:Bind in child user controls

Viewed 22

In WPF I use the following pattern sometimes:

public class InnerViewModel {
  public int I {get ;set;}
}

public class OuterViewModel {
  public InnerViewModel Inner { get; } = new InnerViewModel();
}

Outer view:

<UserControl x:Class="OuterView" ...>
  <local:InnerView DataContext="{Binding Inner}"/>
</UserControl>

Inner view:

<UserControl x:Class="InnerView" ...>
  <TextBox Value="{Binding I}"/>
</UserControl>

In WinUI 3 I can use x:Bind instead of Binding. That comes often with a ViewModel property in the code behind file of the view:

public sealed partial class OuterView : UserControl {
    public OuterViewModel ViewModel {
        get;
    }
    public OuterView() {
        this.InitializeComponent();
        this.ViewModel = App.GetRequiredService<OuterViewModel>(); 
    }
}

and

<UserControl x:Class="OuterView" ...>
  <local:InnerView DataContext="{x:Bind Inner}"/>
</UserControl>

But for InnerView I cannot use x:Bind, since it does not work with DataContext. Is there any way to initialized something like a ViewModel-property of the InnerView in a similar way as the DataContext-binding? Or is it just not possible to apply this pattern to the x:Bind-approach?

1 Answers

I figured out: x:Bind works also with non-dependency properties, so I can do the following:

public sealed partial class InnerView : UserControl {
    public InnerViewModel? ViewModel {
        get; set;
    }
    public InnerView() {
        this.InitializeComponent();
    }
}
<UserControl x:Class="OuterView" ...>
  <local:InnerView ViewModel="{x:Bind Inner}"/>
</UserControl>

and

<UserControl x:Class="InnerView" ...>
  <TextBox Value="{x:Bind ViewModel.I}"/>
</UserControl>

InnerView.ViewModel is not initialized in the constructor, so it needs a setter, but it seems to work.

Related