1

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?

MarkusParker
  • 1,264
  • 2
  • 17
  • 35

1 Answers1

1

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.

MarkusParker
  • 1,264
  • 2
  • 17
  • 35
  • I'm not saying that [UserControls shouldn't have ViewModels](https://stackoverflow.com/questions/1939345/should-a-user-control-have-its-own-view-model), but does ``OuterControl`` and ``InnerControl`` really need their own ViewModels? Are you planning to make tests for those ViewModels? If not, I'd implement them in code-behind. – Andrew KeepCoding Aug 25 '22 at 01:12
  • In my actual code I use the inner view at two places, that is why I separated the xaml-code in its own control. – MarkusParker Aug 25 '22 at 06:59