My ViewModel:
public class MainViewModel : INotifyPropertyChanged
{
private User selectedUser;
private IUserRepository _userRepository;
public List<User> Users { get; set; }
public User SelectedUser
{
get { return selectedUser; }
set
{
selectedUser = value;
OnPropertyChanged("SelectedUser");
}
}
public MainViewModel(IUserRepository userRepository)
{
_userRepository = userRepository;
Users = GetAllUsers();
}
public List<User> GetAllUsers()
{
var users = _userRepository.GetAllUsers();
return users;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
My View:
<Window x:Class="AppDesc.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:vm="clr-namespace:AppDesc.ViewModels"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="14" />
</Style>
<Style TargetType="TextBox">
<Setter Property="FontSize" Value="14" />
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="0.8*" />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding Users}"
SelectedItem="{Binding SelectedUser}" Background="#FFA68F8F">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock FontSize="18" Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Login}" />
<TextBlock Text="{Binding Path=Password}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Column="1" DataContext="{Binding SelectedUser}" Background="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="Выбранный элемент" />
<TextBlock Text="ФИО" />
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="Логин" />
<TextBox Text="{Binding Login, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="Телефон" />
<TextBox Text="{Binding TelephoneNumber, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Grid>
</Window>
Code Behind my View:
I tried to assign my ViewModel to the DataContext in the Code Behind, but an error occurs because my view model has a constructor with parameters. How to correctly connect the view model and the view itself, if the constructor in the ViewModel takes parameters?