Donate

MVVM Basics With TextBlock Control

Hello,

This post is based on the article Understanding the basics of MVVM design pattern. The author demonstrated the basics of MVVM using TextBlock controls. However, the code samples have several issues and in order for the sample application to work, I revise them with the following changes. BindableBase.cs - since SetProperty method uses T in it's parameter, you also need to reference T in your classname.
public class BindableBase<T> : INotifyPropertyChanged
{
   ...
}
MainPageViewModel.cs - update the code in the constructor to bind a single object to the TextBlock controls.
public class MainPageViewModel : BindableBase<Book>
{
 private Book _book;

 public Book Book
 { 
  get
  {
   return _book;
  } 
  set
  {
   SetProperty(ref _book, value);
  } 
 }
 
 public MainPageViewModel()
 {           
  Book = new Book()
  {
   Title = "Harry Potter",
   Author = "J. K. Rowling",
   Category = "Young-adult fiction",
   Language = "English"
  };
 }
}
XAML - Prefix the properties with the classname when binding it with the control
<TextBlock x:Name="bookTitle" HorizontalAlignment="Left" TextWrapping="Wrap" Grid.Row="0" Width="500" Text="{Binding Book.Title}" />


Hope it helps! :-)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input