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?