Bind DataContext to ViewModel in WPF

Last Updated on February 8, 2024

<Window x:Class="desktop.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
        xmlns:svgc="http://sharpvectors.codeplex.com/svgc/"
        xmlns:local="clr-namespace:desktop.viewmodel"
        Title="Monitoring" Height="350" Width="525" Loaded="MainWindow_OnLoaded" WindowState="Maximized">
    <Window.DataContext>
        <local:MainWindowViewModel x:Key="ViewModel" />
    </Window.DataContext>
    <DockPanel>
        <telerik:RadMenu Name="MenuMain" VerticalAlignment="Top" DockPanel.Dock="Top">
            <telerik:RadMenuItem Header="Item 1">
                <telerik:RadMenuItem Header="SubItem 1" />
                <telerik:RadMenuItem Header="SubItem 2" />
            </telerik:RadMenuItem>
            <telerik:RadMenuItem Header="Item 2" />
        </telerik:RadMenu>
        <telerik:RadBusyIndicator IsBusy="{Binding  Path=IsBusyIndicatorBusy}">
            <Frame Name="FrameMain" NavigationUIVisibility="Hidden" />
        </telerik:RadBusyIndicator>

    </DockPanel>
</Window>
public partial class MainWindow : Window
    {
        public MainWindowViewModel ViewModel { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            ViewModel = (MainWindowViewModel) DataContext;
        }
     }

ViewModelBase

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
    {
        if(!EqualityComparer<T>.Default.Equals(field, newValue))
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            return true;
        }
        return false;
    }
}

ViewModel

using System.ComponentModel;
using System.Runtime.CompilerServices;
using desktop.Annotations;
using Telerik.Windows.Controls;

namespace desktop.viewmodel
{
    public class MainWindowViewModel : ViewModelBase
    {

        private bool _isBusyIndicatorBusy = false;

        public bool IsBusyIndicatorBusy
        {
            get => _isBusyIndicatorBusy;
            set
            {
                _isBusyIndicatorBusy = value;
                SetProperty(ref _isBusyIndicatorBusy , value);
            }
        }
    }
}

References
https://stackoverflow.com/questions/25267070/setting-datacontext-of-elements-inside-xaml
https://intellitect.com/blog/getting-started-model-view-viewmodel-mvvm-pattern-using-windows-presentation-framework-wpf/