Assuming I have a window that looks something like this:
<Window>
<Window.Resources>
<ResourceDictionary>
<controllers:MainWindowController x:Key="Controller" />
</ResourceDictionary>
</Window.Resources>
<Window.DataContext>
<Binding Source="{StaticResource Controller}" />
</Window.DataContext>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox Grid.Row="0"
Margin="0, 0, 0, 2.5"
ItemsSource="{Binding Users}"
SelectedItem="{Binding SelectedUser, Mode=OneWayToSource}" />
<Button Grid.Row="1"
Margin="0, 2.5, 0, 0"
Command="{Binding DisplayUserInfoCommand}" />
</Grid>
</Window>
and the MainWindowController class is something like:
public sealed class MainWindowController : ReactiveObject
{
public ObservableCollection<User> Users { get; } = new ObservableCollection<User>();
public User SelectedUser { get; set; }
public ReactiveCommand<Unit, Unit> DisplaySelectedUserInfoCommand { get; }
public MainWindowController()
{
DisplaySelectedUserInfoCommand = ReactiveCommand.Create(DisplaySelectedUserInfoCommandHandler);
}
private void DisplaySelectedUserInfoCommandHandler()
{
if (SelectedUser == null) return;
// TODO: pass SelectedUser to the newly created UserInfoWindow.
_ = new UserInfoWindow().ShowDialog();
}
}
the User is a record that looks like this:
public sealed record User(string Name, string Email, string Phone);
and the UserInfoWindow is something like:
<Window>
<Window.Resources>
<ResourceDictionary>
<controllers:UserInfoWindowController x:Key="Controller" />
</ResourceDictionary>
</Window.Resources>
<Window.DataContext>
<Binding Source="{StaticResource Controller}" />
</Window.DataContext>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Row="0"
Margin="0, 0, 0, 2.5"
Content="{Binding User.Name}"
ContentStringFormat="Name: {0}" />
<Label Grid.Row="1"
Margin="0, 2.5, 0, 2.5"
Content="{Binding User.Email}"
ContentStringFormat="Email: {0}" />
<Label Grid.Row="2"
Margin="0, 2.5, 0, 0"
Content="{Binding User.Phone}"
ContentStringFormat="Phone: {0}" />
</Grid>
</Window>
and the UserInfoWindowController is something like this:
public sealed class UserInfoWindowController : ReactiveObject
{
private User _user;
public User User
{
get => _user;
set => this.RaiseAndSetIfChanged(ref _user, value);
}
}
how can I pass the SelectedUser from the MainWindowController to the newly created UserInfoWindow without manually passing a new instance of UserInfoWindowController to it upon its creation or setting the DataContext via code?
Notes:
The XAML code above isn't "complete" since I have stripped some unnecessary attributes for the sake of keeping the post short.
I've omitted the
usingdirectives from the C# code for the same reason as above.I'm using ReactiveUI.
My WPF application is using .NET 5.
_ = new UserInfoWindow().ShowDialog()in the examples above.