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

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid