Hello, tell me, please, how to search not in Code Behind ? There is a table with books, the user enters ID, and the program should display data about the book on the screen. How to do this with the help of events is understandable, but with the help of commands? I do not know how to pass the entered id in MainWindowViewModel.cs - the class created to implement the logic of MainWindow . It has a Search command that should go through the list and find a book on ID. I tried it through the constructor, as it is the first one that is called and gives errors. Perhaps there is some way? Thanks in advance.
Who cares, thanks to you, got this working version of this task:
Haml:
<StackPanel Grid.Row="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" Orientation="Horizontal"> <TextBox Height="30" Width="140" x:Name="IdSearchTextBox" Margin="2"></TextBox> <Button Name="SearchButton" Content="Search by Id" Height="30" Width="120" Margin="2" Command="{Binding Search}" CommandParameter="{Binding ElementName=IdSearchTextBox, Path=Text}"></Button> </StackPanel> <Label Content="Book" FontSize="18" Grid.Row="1" Grid.Column="0" Margin="5" HorizontalAlignment="Left" Width="200"></Label> <TextBox Grid.Row="1" Text="{Binding CurrentBook.Nom}" Grid.Column="1" x:Name="BookTextBox" Margin="5" Width="400"/> <Label Content="Auteur" FontSize="18" Grid.Row="2" Grid.Column="0" Margin="5" HorizontalAlignment="Left" Width="200"></Label> <TextBox Grid.Row="2" Text="{Binding CurrentBook.Auteur}" Grid.Column="1" x:Name="AuteurTextBox" Margin="5" Width="400"/> <Label Content="Description" FontSize="18" Grid.Row="3" Grid.Column="0" Margin="5" HorizontalAlignment="Left" Width="200"></Label> <TextBox Grid.Row="3" Text="{Binding CurrentBook.Description}" Grid.Column="1" x:Name="DescriptionTextBox" Margin="5" Width="400" Height="150"/> View - there is nothing, except for initializing the view model (This is important, as it turned out)))
public MainWindow() { InitializeComponent(); DataContext = new MainWindowViewModel(); } Viewmodel
private Book _currentBook; private RelayCommand<String> _search; private ObservableCollection<Book> _books; public Book CurrentBook { get { return _currentBook; } set { _currentBook = value; FirePropertyChanged(); } } public RelayCommand<string> Search { get { return _search; } set { _search = value; } } public ObservableCollection<Book> Books { get { return _books; } set { _books = value; FirePropertyChanged(); } } public MainWindowViewModel() { Books = new ObservableCollection<Book>(_conn.Books); Search = new RelayCommand<string>(SearchById); } public void SearchById(string str) { _id = Convert.ToInt32(str); foreach (Book b in Books) { if (b.Id == Convert.ToInt32(str)) { CurrentBook = b; } } } It is advisable, of course, to try to check the whole thing, but check it out, thanks to everyone !!