kandi background
Explore Kits

mvvmlight | main purpose of the toolkit is to accelerate the creation | Form library

 by   lbugnion C# Version: Current License: MIT

 by   lbugnion C# Version: Current License: MIT

Download this library from

kandi X-RAY | mvvmlight Summary

mvvmlight is a C# library typically used in User Interface, Form, Xamarin applications. mvvmlight has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UWP, Windows Presentation Foundation (WPF), Silverlight, Windows Phone.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • mvvmlight has a medium active ecosystem.
  • It has 1010 star(s) with 246 fork(s). There are 68 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 56 open issues and 30 have been closed. On average issues are closed in 89 days. There are 16 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of mvvmlight is current.
mvvmlight Support
Best in #Form
Average in #Form
mvvmlight Support
Best in #Form
Average in #Form

quality kandi Quality

  • mvvmlight has 0 bugs and 0 code smells.
mvvmlight Quality
Best in #Form
Average in #Form
mvvmlight Quality
Best in #Form
Average in #Form

securitySecurity

  • mvvmlight has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • mvvmlight code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
mvvmlight Security
Best in #Form
Average in #Form
mvvmlight Security
Best in #Form
Average in #Form

license License

  • mvvmlight is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
mvvmlight License
Best in #Form
Average in #Form
mvvmlight License
Best in #Form
Average in #Form

buildReuse

  • mvvmlight releases are not available. You will need to build from source code and install.
  • Installation instructions are available. Examples and code snippets are not available.
mvvmlight Reuse
Best in #Form
Average in #Form
mvvmlight Reuse
Best in #Form
Average in #Form
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

mvvmlight Key Features

The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UWP, Windows Presentation Foundation (WPF), Silverlight, Windows Phone.

How can I change IsInDesignMode to use it in Microsoft.Toolkit.MVVM?

copy iconCopydownload iconDownload
internal class View : Window
{
    public View()
    {
        Model.IsInDesignMode = () => DesignerProperties.GetIsInDesignMode(this);
    }

    private Model Model => DataContext as Model ?? throw new InvalidOperationException();
}

internal class Model
{
    public Func<bool> IsInDesignMode { get; set; }

    public Model()
    {
        if (IsInDesignMode is null)
            throw new InvalidOperationException();

        if (IsInDesignMode())
        {
            int i;
        }
        else
        {
            int i;
        }
    }
}

CommandParameter not passed to CanExecute when databound within a DataGrid (CanExecute parameter is null)

copy iconCopydownload iconDownload
CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Self}}"
public class MainWindowVM : ObservableObject
{
    public MainWindowVM()
    {
        TestData = new ObservableCollection<TestModel>
    {
        new TestModel() {Name = "Test1"},
        new TestModel() {Name = "Test2"},
        new TestModel() {Name = "Test3"}
    };

        DeleteCommand = new RelayCommand<object>(Delete, CanDelete);
    }

    public IRelayCommand<object> DeleteCommand { get; }

    private void Delete(object parameter)
    {
        if (parameter is TestModel model)
        {
            //do stuff
        }
    }

    private bool CanDelete(object parameter)
    {
        if (parameter is TestModel model && model.Name == "Test2")
        {
            return false;
        }
        return true;
    }

    public ObservableCollection<TestModel> TestData
    {
        get => _testData;
        set => SetProperty(ref _testData, value);
    }
    private ObservableCollection<TestModel> _testData;
}
CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Self}}"
public class MainWindowVM : ObservableObject
{
    public MainWindowVM()
    {
        TestData = new ObservableCollection<TestModel>
    {
        new TestModel() {Name = "Test1"},
        new TestModel() {Name = "Test2"},
        new TestModel() {Name = "Test3"}
    };

        DeleteCommand = new RelayCommand<object>(Delete, CanDelete);
    }

    public IRelayCommand<object> DeleteCommand { get; }

    private void Delete(object parameter)
    {
        if (parameter is TestModel model)
        {
            //do stuff
        }
    }

    private bool CanDelete(object parameter)
    {
        if (parameter is TestModel model && model.Name == "Test2")
        {
            return false;
        }
        return true;
    }

    public ObservableCollection<TestModel> TestData
    {
        get => _testData;
        set => SetProperty(ref _testData, value);
    }
    private ObservableCollection<TestModel> _testData;
}

C# JsonIgnore to basic class

copy iconCopydownload iconDownload
public class ShouldSerializeContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.DeclaringType == typeof(ViewModelBase) && property.PropertyName == "IsInDesignMode")
        {
            property.ShouldSerialize = x=> false;
        }

        return property;
    }
}
var result = JsonConvert.SerializeObject(
    data,
    Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver() }
);
public class ShouldSerializeContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.DeclaringType == typeof(ViewModelBase) && property.PropertyName == "IsInDesignMode")
        {
            property.ShouldSerialize = x=> false;
        }

        return property;
    }
}
var result = JsonConvert.SerializeObject(
    data,
    Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver() }
);
[JsonObject(MemberSerialization.OptIn)]

Declaring Design-Time ViewModel for Avalonia Window

copy iconCopydownload iconDownload
class DesignData
{
    public MyViewModel MyViewModel => new MyViewModel(...);
}

GalaSoft MvvmLight not disabling UserControl with RelayCommand

copy iconCopydownload iconDownload
public partial class ShortcutButton : UserControl, ICommandSource
{
  public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ICommand), OnCommandChanged));

  public ICommand Command
  {
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
  }

  private bool OriginalIsEnabledValue { get; set; }
  private bool IsEnabledChangedByCommandCanExecute { get; set; }

  public ShortcutButton()
  {
    this.OriginalIsEnabledValue = this.IsEnabled;
    this.IsEnabledChanged += OnIsEnabledChanged;
  }

  private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (this.IsEnabledChangedByCommandCanExecute)
    {
      return;
    }
    
    this.OriginalIsEnabledValue = (bool)e.NewValue;    
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    if (e.OldValue is ICommand oldCommand)
    {
      CanExecuteChangedEventManager.RemoveHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }

    if (e.NewValue is ICommand newCommand)
    {
      CanExecuteChangedEventManager.AddHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }
  }

  private void OnCommandCanExecuteChanged(object sender, EventArgs e)
  {
    this.IsEnabledChangedByCommandCanExecute = true;
    this.IsEnabled = this.OriginalIsEnabledValue 
      && this.Command.CanExecute(this.CommandParameter);
    this.IsEnabledChangedByCommandCanExecute = false;
  }
}
<Window>
  <Window.InputBindings>
    <KeyBinding Key="F2" Command="{Binding EditCommand, Mode=OneTime}" />
  </Window.InputBindings>
</Window>
public class ShortcutButton : Button
{
  public static readonly DependencyProperty ShortcutModifierKeysProperty =
      DependencyProperty.Register(
        "ShortcutModifierKeys",
        typeof(ModifierKeys),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ModifierKeys), OnShortcutModifierKeysChanged));

  public ModifierKeys ShortcutModifierKeys
  {
    get => (ModifierKeys)GetValue(ShortcutModifierKeysProperty);
    set => SetValue(ShortcutModifierKeysProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyProperty =
      DependencyProperty.Register(
        "ShortcutKey",
        typeof(Key),
        typeof(ShortcutButton),
        new PropertyMetadata(default(Key), OnShortcutKeyChanged));

  public Key ShortcutKey
  {
    get => (Key)GetValue(ShortcutKeyProperty);
    set => SetValue(ShortcutKeyProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyTargetProperty =
      DependencyProperty.Register(
        "ShortcutKeyTarget",
        typeof(UIElement),
        typeof(ShortcutButton),
        new PropertyMetadata(default(UIElement), OnShortcutKeyTargetChanged));

  public UIElement ShortcutKeyTarget
  {
    get => (UIElement)GetValue(ShortcutKeyTargetProperty);
    set => SetValue(ShortcutKeyTargetProperty, value);
  }

  private static readonly DependencyPropertyKey ShortcutKeyDisplayTextPropertyKey =
      DependencyProperty.RegisterReadOnly(
        "ShortcutKeyDisplayText",
        typeof(string),
        typeof(ShortcutButton),
        new PropertyMetadata(default(string)));

  public static readonly DependencyProperty ShortcutKeyDisplayTextProperty = ShortcutKeyDisplayTextPropertyKey.DependencyProperty;

  public string ShortcutKeyDisplayText
  {
    get => (string)GetValue(ShortcutKeyDisplayTextProperty);
    private set => SetValue(ShortcutKeyDisplayTextPropertyKey, value);
  }

  private KeyBinding ShortcutKeyBinding { get; set; }

  static ShortcutButton()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(typeof(ShortcutButton)));
    CommandProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(OnCommandChanged));
  }

  private static void OnShortcutModifierKeysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }


  private void UpdateShortcutKeyBinding()
  {
    this.ShortcutKeyDisplayText = this.ShortcutModifierKeys != ModifierKeys.None 
      ? $"{this.ShortcutModifierKeys}+{this.ShortcutKey}" 
      : this.ShortcutKey.ToString();

    if (this.Command == null || this.ShortcutKeyTarget == null)
    {
      return;
    }

    this.ShortcutKeyTarget.InputBindings.Remove(this.ShortcutKeyBinding);

    this.ShortcutKeyBinding = new KeyBinding(this.Command, this.ShortcutKey, this.ShortcutModifierKeys);
    this.ShortcutKeyBinding.Freeze();
    this.ShortcutKeyTarget.InputBindings.Add(this.ShortcutKeyBinding);
  }
}
<Style TargetType="{x:Type local:ShortcutButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:ShortcutButton}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <StackPanel>
            <TextBlock Text="{TemplateBinding ShortcutKeyDisplayText}" />
            <ContentPresenter />
          </StackPanel>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Window x:Name="Window">
  <local:ShortcutButton Content="Edit"
                        Command="{Binding EditCommand}" 
                        ShortcutKey="{x:Static Key.F2}" 
                        ShortcutModifierKeys="{x:Static ModifierKeys.Alt}"
                        ShortcutKeyTarget="{Binding ElementName=Window}" />
</Window>
public partial class ShortcutButton : UserControl, ICommandSource
{
  public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ICommand), OnCommandChanged));

  public ICommand Command
  {
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
  }

  private bool OriginalIsEnabledValue { get; set; }
  private bool IsEnabledChangedByCommandCanExecute { get; set; }

  public ShortcutButton()
  {
    this.OriginalIsEnabledValue = this.IsEnabled;
    this.IsEnabledChanged += OnIsEnabledChanged;
  }

  private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (this.IsEnabledChangedByCommandCanExecute)
    {
      return;
    }
    
    this.OriginalIsEnabledValue = (bool)e.NewValue;    
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    if (e.OldValue is ICommand oldCommand)
    {
      CanExecuteChangedEventManager.RemoveHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }

    if (e.NewValue is ICommand newCommand)
    {
      CanExecuteChangedEventManager.AddHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }
  }

  private void OnCommandCanExecuteChanged(object sender, EventArgs e)
  {
    this.IsEnabledChangedByCommandCanExecute = true;
    this.IsEnabled = this.OriginalIsEnabledValue 
      && this.Command.CanExecute(this.CommandParameter);
    this.IsEnabledChangedByCommandCanExecute = false;
  }
}
<Window>
  <Window.InputBindings>
    <KeyBinding Key="F2" Command="{Binding EditCommand, Mode=OneTime}" />
  </Window.InputBindings>
</Window>
public class ShortcutButton : Button
{
  public static readonly DependencyProperty ShortcutModifierKeysProperty =
      DependencyProperty.Register(
        "ShortcutModifierKeys",
        typeof(ModifierKeys),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ModifierKeys), OnShortcutModifierKeysChanged));

  public ModifierKeys ShortcutModifierKeys
  {
    get => (ModifierKeys)GetValue(ShortcutModifierKeysProperty);
    set => SetValue(ShortcutModifierKeysProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyProperty =
      DependencyProperty.Register(
        "ShortcutKey",
        typeof(Key),
        typeof(ShortcutButton),
        new PropertyMetadata(default(Key), OnShortcutKeyChanged));

  public Key ShortcutKey
  {
    get => (Key)GetValue(ShortcutKeyProperty);
    set => SetValue(ShortcutKeyProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyTargetProperty =
      DependencyProperty.Register(
        "ShortcutKeyTarget",
        typeof(UIElement),
        typeof(ShortcutButton),
        new PropertyMetadata(default(UIElement), OnShortcutKeyTargetChanged));

  public UIElement ShortcutKeyTarget
  {
    get => (UIElement)GetValue(ShortcutKeyTargetProperty);
    set => SetValue(ShortcutKeyTargetProperty, value);
  }

  private static readonly DependencyPropertyKey ShortcutKeyDisplayTextPropertyKey =
      DependencyProperty.RegisterReadOnly(
        "ShortcutKeyDisplayText",
        typeof(string),
        typeof(ShortcutButton),
        new PropertyMetadata(default(string)));

  public static readonly DependencyProperty ShortcutKeyDisplayTextProperty = ShortcutKeyDisplayTextPropertyKey.DependencyProperty;

  public string ShortcutKeyDisplayText
  {
    get => (string)GetValue(ShortcutKeyDisplayTextProperty);
    private set => SetValue(ShortcutKeyDisplayTextPropertyKey, value);
  }

  private KeyBinding ShortcutKeyBinding { get; set; }

  static ShortcutButton()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(typeof(ShortcutButton)));
    CommandProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(OnCommandChanged));
  }

  private static void OnShortcutModifierKeysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }


  private void UpdateShortcutKeyBinding()
  {
    this.ShortcutKeyDisplayText = this.ShortcutModifierKeys != ModifierKeys.None 
      ? $"{this.ShortcutModifierKeys}+{this.ShortcutKey}" 
      : this.ShortcutKey.ToString();

    if (this.Command == null || this.ShortcutKeyTarget == null)
    {
      return;
    }

    this.ShortcutKeyTarget.InputBindings.Remove(this.ShortcutKeyBinding);

    this.ShortcutKeyBinding = new KeyBinding(this.Command, this.ShortcutKey, this.ShortcutModifierKeys);
    this.ShortcutKeyBinding.Freeze();
    this.ShortcutKeyTarget.InputBindings.Add(this.ShortcutKeyBinding);
  }
}
<Style TargetType="{x:Type local:ShortcutButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:ShortcutButton}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <StackPanel>
            <TextBlock Text="{TemplateBinding ShortcutKeyDisplayText}" />
            <ContentPresenter />
          </StackPanel>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Window x:Name="Window">
  <local:ShortcutButton Content="Edit"
                        Command="{Binding EditCommand}" 
                        ShortcutKey="{x:Static Key.F2}" 
                        ShortcutModifierKeys="{x:Static ModifierKeys.Alt}"
                        ShortcutKeyTarget="{Binding ElementName=Window}" />
</Window>
public partial class ShortcutButton : UserControl, ICommandSource
{
  public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ICommand), OnCommandChanged));

  public ICommand Command
  {
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
  }

  private bool OriginalIsEnabledValue { get; set; }
  private bool IsEnabledChangedByCommandCanExecute { get; set; }

  public ShortcutButton()
  {
    this.OriginalIsEnabledValue = this.IsEnabled;
    this.IsEnabledChanged += OnIsEnabledChanged;
  }

  private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (this.IsEnabledChangedByCommandCanExecute)
    {
      return;
    }
    
    this.OriginalIsEnabledValue = (bool)e.NewValue;    
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    if (e.OldValue is ICommand oldCommand)
    {
      CanExecuteChangedEventManager.RemoveHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }

    if (e.NewValue is ICommand newCommand)
    {
      CanExecuteChangedEventManager.AddHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }
  }

  private void OnCommandCanExecuteChanged(object sender, EventArgs e)
  {
    this.IsEnabledChangedByCommandCanExecute = true;
    this.IsEnabled = this.OriginalIsEnabledValue 
      && this.Command.CanExecute(this.CommandParameter);
    this.IsEnabledChangedByCommandCanExecute = false;
  }
}
<Window>
  <Window.InputBindings>
    <KeyBinding Key="F2" Command="{Binding EditCommand, Mode=OneTime}" />
  </Window.InputBindings>
</Window>
public class ShortcutButton : Button
{
  public static readonly DependencyProperty ShortcutModifierKeysProperty =
      DependencyProperty.Register(
        "ShortcutModifierKeys",
        typeof(ModifierKeys),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ModifierKeys), OnShortcutModifierKeysChanged));

  public ModifierKeys ShortcutModifierKeys
  {
    get => (ModifierKeys)GetValue(ShortcutModifierKeysProperty);
    set => SetValue(ShortcutModifierKeysProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyProperty =
      DependencyProperty.Register(
        "ShortcutKey",
        typeof(Key),
        typeof(ShortcutButton),
        new PropertyMetadata(default(Key), OnShortcutKeyChanged));

  public Key ShortcutKey
  {
    get => (Key)GetValue(ShortcutKeyProperty);
    set => SetValue(ShortcutKeyProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyTargetProperty =
      DependencyProperty.Register(
        "ShortcutKeyTarget",
        typeof(UIElement),
        typeof(ShortcutButton),
        new PropertyMetadata(default(UIElement), OnShortcutKeyTargetChanged));

  public UIElement ShortcutKeyTarget
  {
    get => (UIElement)GetValue(ShortcutKeyTargetProperty);
    set => SetValue(ShortcutKeyTargetProperty, value);
  }

  private static readonly DependencyPropertyKey ShortcutKeyDisplayTextPropertyKey =
      DependencyProperty.RegisterReadOnly(
        "ShortcutKeyDisplayText",
        typeof(string),
        typeof(ShortcutButton),
        new PropertyMetadata(default(string)));

  public static readonly DependencyProperty ShortcutKeyDisplayTextProperty = ShortcutKeyDisplayTextPropertyKey.DependencyProperty;

  public string ShortcutKeyDisplayText
  {
    get => (string)GetValue(ShortcutKeyDisplayTextProperty);
    private set => SetValue(ShortcutKeyDisplayTextPropertyKey, value);
  }

  private KeyBinding ShortcutKeyBinding { get; set; }

  static ShortcutButton()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(typeof(ShortcutButton)));
    CommandProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(OnCommandChanged));
  }

  private static void OnShortcutModifierKeysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }


  private void UpdateShortcutKeyBinding()
  {
    this.ShortcutKeyDisplayText = this.ShortcutModifierKeys != ModifierKeys.None 
      ? $"{this.ShortcutModifierKeys}+{this.ShortcutKey}" 
      : this.ShortcutKey.ToString();

    if (this.Command == null || this.ShortcutKeyTarget == null)
    {
      return;
    }

    this.ShortcutKeyTarget.InputBindings.Remove(this.ShortcutKeyBinding);

    this.ShortcutKeyBinding = new KeyBinding(this.Command, this.ShortcutKey, this.ShortcutModifierKeys);
    this.ShortcutKeyBinding.Freeze();
    this.ShortcutKeyTarget.InputBindings.Add(this.ShortcutKeyBinding);
  }
}
<Style TargetType="{x:Type local:ShortcutButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:ShortcutButton}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <StackPanel>
            <TextBlock Text="{TemplateBinding ShortcutKeyDisplayText}" />
            <ContentPresenter />
          </StackPanel>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Window x:Name="Window">
  <local:ShortcutButton Content="Edit"
                        Command="{Binding EditCommand}" 
                        ShortcutKey="{x:Static Key.F2}" 
                        ShortcutModifierKeys="{x:Static ModifierKeys.Alt}"
                        ShortcutKeyTarget="{Binding ElementName=Window}" />
</Window>
public partial class ShortcutButton : UserControl, ICommandSource
{
  public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ICommand), OnCommandChanged));

  public ICommand Command
  {
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
  }

  private bool OriginalIsEnabledValue { get; set; }
  private bool IsEnabledChangedByCommandCanExecute { get; set; }

  public ShortcutButton()
  {
    this.OriginalIsEnabledValue = this.IsEnabled;
    this.IsEnabledChanged += OnIsEnabledChanged;
  }

  private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (this.IsEnabledChangedByCommandCanExecute)
    {
      return;
    }
    
    this.OriginalIsEnabledValue = (bool)e.NewValue;    
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    if (e.OldValue is ICommand oldCommand)
    {
      CanExecuteChangedEventManager.RemoveHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }

    if (e.NewValue is ICommand newCommand)
    {
      CanExecuteChangedEventManager.AddHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }
  }

  private void OnCommandCanExecuteChanged(object sender, EventArgs e)
  {
    this.IsEnabledChangedByCommandCanExecute = true;
    this.IsEnabled = this.OriginalIsEnabledValue 
      && this.Command.CanExecute(this.CommandParameter);
    this.IsEnabledChangedByCommandCanExecute = false;
  }
}
<Window>
  <Window.InputBindings>
    <KeyBinding Key="F2" Command="{Binding EditCommand, Mode=OneTime}" />
  </Window.InputBindings>
</Window>
public class ShortcutButton : Button
{
  public static readonly DependencyProperty ShortcutModifierKeysProperty =
      DependencyProperty.Register(
        "ShortcutModifierKeys",
        typeof(ModifierKeys),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ModifierKeys), OnShortcutModifierKeysChanged));

  public ModifierKeys ShortcutModifierKeys
  {
    get => (ModifierKeys)GetValue(ShortcutModifierKeysProperty);
    set => SetValue(ShortcutModifierKeysProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyProperty =
      DependencyProperty.Register(
        "ShortcutKey",
        typeof(Key),
        typeof(ShortcutButton),
        new PropertyMetadata(default(Key), OnShortcutKeyChanged));

  public Key ShortcutKey
  {
    get => (Key)GetValue(ShortcutKeyProperty);
    set => SetValue(ShortcutKeyProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyTargetProperty =
      DependencyProperty.Register(
        "ShortcutKeyTarget",
        typeof(UIElement),
        typeof(ShortcutButton),
        new PropertyMetadata(default(UIElement), OnShortcutKeyTargetChanged));

  public UIElement ShortcutKeyTarget
  {
    get => (UIElement)GetValue(ShortcutKeyTargetProperty);
    set => SetValue(ShortcutKeyTargetProperty, value);
  }

  private static readonly DependencyPropertyKey ShortcutKeyDisplayTextPropertyKey =
      DependencyProperty.RegisterReadOnly(
        "ShortcutKeyDisplayText",
        typeof(string),
        typeof(ShortcutButton),
        new PropertyMetadata(default(string)));

  public static readonly DependencyProperty ShortcutKeyDisplayTextProperty = ShortcutKeyDisplayTextPropertyKey.DependencyProperty;

  public string ShortcutKeyDisplayText
  {
    get => (string)GetValue(ShortcutKeyDisplayTextProperty);
    private set => SetValue(ShortcutKeyDisplayTextPropertyKey, value);
  }

  private KeyBinding ShortcutKeyBinding { get; set; }

  static ShortcutButton()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(typeof(ShortcutButton)));
    CommandProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(OnCommandChanged));
  }

  private static void OnShortcutModifierKeysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }


  private void UpdateShortcutKeyBinding()
  {
    this.ShortcutKeyDisplayText = this.ShortcutModifierKeys != ModifierKeys.None 
      ? $"{this.ShortcutModifierKeys}+{this.ShortcutKey}" 
      : this.ShortcutKey.ToString();

    if (this.Command == null || this.ShortcutKeyTarget == null)
    {
      return;
    }

    this.ShortcutKeyTarget.InputBindings.Remove(this.ShortcutKeyBinding);

    this.ShortcutKeyBinding = new KeyBinding(this.Command, this.ShortcutKey, this.ShortcutModifierKeys);
    this.ShortcutKeyBinding.Freeze();
    this.ShortcutKeyTarget.InputBindings.Add(this.ShortcutKeyBinding);
  }
}
<Style TargetType="{x:Type local:ShortcutButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:ShortcutButton}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <StackPanel>
            <TextBlock Text="{TemplateBinding ShortcutKeyDisplayText}" />
            <ContentPresenter />
          </StackPanel>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Window x:Name="Window">
  <local:ShortcutButton Content="Edit"
                        Command="{Binding EditCommand}" 
                        ShortcutKey="{x:Static Key.F2}" 
                        ShortcutModifierKeys="{x:Static ModifierKeys.Alt}"
                        ShortcutKeyTarget="{Binding ElementName=Window}" />
</Window>
public partial class ShortcutButton : UserControl, ICommandSource
{
  public static readonly DependencyProperty CommandProperty =
      DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ICommand), OnCommandChanged));

  public ICommand Command
  {
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
  }

  private bool OriginalIsEnabledValue { get; set; }
  private bool IsEnabledChangedByCommandCanExecute { get; set; }

  public ShortcutButton()
  {
    this.OriginalIsEnabledValue = this.IsEnabled;
    this.IsEnabledChanged += OnIsEnabledChanged;
  }

  private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
  {
    if (this.IsEnabledChangedByCommandCanExecute)
    {
      return;
    }
    
    this.OriginalIsEnabledValue = (bool)e.NewValue;    
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    if (e.OldValue is ICommand oldCommand)
    {
      CanExecuteChangedEventManager.RemoveHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }

    if (e.NewValue is ICommand newCommand)
    {
      CanExecuteChangedEventManager.AddHandler(this_.Command, this_.OnCommandCanExecuteChanged);
    }
  }

  private void OnCommandCanExecuteChanged(object sender, EventArgs e)
  {
    this.IsEnabledChangedByCommandCanExecute = true;
    this.IsEnabled = this.OriginalIsEnabledValue 
      && this.Command.CanExecute(this.CommandParameter);
    this.IsEnabledChangedByCommandCanExecute = false;
  }
}
<Window>
  <Window.InputBindings>
    <KeyBinding Key="F2" Command="{Binding EditCommand, Mode=OneTime}" />
  </Window.InputBindings>
</Window>
public class ShortcutButton : Button
{
  public static readonly DependencyProperty ShortcutModifierKeysProperty =
      DependencyProperty.Register(
        "ShortcutModifierKeys",
        typeof(ModifierKeys),
        typeof(ShortcutButton),
        new PropertyMetadata(default(ModifierKeys), OnShortcutModifierKeysChanged));

  public ModifierKeys ShortcutModifierKeys
  {
    get => (ModifierKeys)GetValue(ShortcutModifierKeysProperty);
    set => SetValue(ShortcutModifierKeysProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyProperty =
      DependencyProperty.Register(
        "ShortcutKey",
        typeof(Key),
        typeof(ShortcutButton),
        new PropertyMetadata(default(Key), OnShortcutKeyChanged));

  public Key ShortcutKey
  {
    get => (Key)GetValue(ShortcutKeyProperty);
    set => SetValue(ShortcutKeyProperty, value);
  }

  public static readonly DependencyProperty ShortcutKeyTargetProperty =
      DependencyProperty.Register(
        "ShortcutKeyTarget",
        typeof(UIElement),
        typeof(ShortcutButton),
        new PropertyMetadata(default(UIElement), OnShortcutKeyTargetChanged));

  public UIElement ShortcutKeyTarget
  {
    get => (UIElement)GetValue(ShortcutKeyTargetProperty);
    set => SetValue(ShortcutKeyTargetProperty, value);
  }

  private static readonly DependencyPropertyKey ShortcutKeyDisplayTextPropertyKey =
      DependencyProperty.RegisterReadOnly(
        "ShortcutKeyDisplayText",
        typeof(string),
        typeof(ShortcutButton),
        new PropertyMetadata(default(string)));

  public static readonly DependencyProperty ShortcutKeyDisplayTextProperty = ShortcutKeyDisplayTextPropertyKey.DependencyProperty;

  public string ShortcutKeyDisplayText
  {
    get => (string)GetValue(ShortcutKeyDisplayTextProperty);
    private set => SetValue(ShortcutKeyDisplayTextPropertyKey, value);
  }

  private KeyBinding ShortcutKeyBinding { get; set; }

  static ShortcutButton()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(typeof(ShortcutButton)));
    CommandProperty.OverrideMetadata(typeof(ShortcutButton), new FrameworkPropertyMetadata(OnCommandChanged));
  }

  private static void OnShortcutModifierKeysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnShortcutKeyTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }

  private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    var this_ = d as ShortcutButton;
    this_.UpdateShortcutKeyBinding();
  }


  private void UpdateShortcutKeyBinding()
  {
    this.ShortcutKeyDisplayText = this.ShortcutModifierKeys != ModifierKeys.None 
      ? $"{this.ShortcutModifierKeys}+{this.ShortcutKey}" 
      : this.ShortcutKey.ToString();

    if (this.Command == null || this.ShortcutKeyTarget == null)
    {
      return;
    }

    this.ShortcutKeyTarget.InputBindings.Remove(this.ShortcutKeyBinding);

    this.ShortcutKeyBinding = new KeyBinding(this.Command, this.ShortcutKey, this.ShortcutModifierKeys);
    this.ShortcutKeyBinding.Freeze();
    this.ShortcutKeyTarget.InputBindings.Add(this.ShortcutKeyBinding);
  }
}
<Style TargetType="{x:Type local:ShortcutButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:ShortcutButton}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <StackPanel>
            <TextBlock Text="{TemplateBinding ShortcutKeyDisplayText}" />
            <ContentPresenter />
          </StackPanel>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Window x:Name="Window">
  <local:ShortcutButton Content="Edit"
                        Command="{Binding EditCommand}" 
                        ShortcutKey="{x:Static Key.F2}" 
                        ShortcutModifierKeys="{x:Static ModifierKeys.Alt}"
                        ShortcutKeyTarget="{Binding ElementName=Window}" />
</Window>

The KeyDown event will not fire, but the exact same code with PreviewMouseLeftButtonDown event will

copy iconCopydownload iconDownload
public partial class AsteroidsView : UserControl
{
    public AsteroidsView()
    {
        InitializeComponent();
        Loaded += AsteroidsView_Loaded;
    }

    private void AsteroidsView_Loaded(object sender, RoutedEventArgs e)
    {
        Window parentWindow = Window.GetWindow(this);
        parentWindow.PreviewKeyDown += ParentWindow_PreviewKeyDown;
    }

    private void ParentWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        //TODO: handle...
    }
}
    public partial class AsteroidsView : UserControl
    {
        public AsteroidsView()
        {
            InitializeComponent();
            Loaded += AsteroidsView_Loaded;
        }

        private void AsteroidsView_Loaded(object sender, RoutedEventArgs e)
        {
            Window parentWindow = Window.GetWindow(this);
            parentWindow.PreviewKeyDown += ParentWindow_PreviewKeyDown;
        }

        private void ParentWindow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Keyboard.Focus(this.MyCanvas);  // `this` keyword is redundant
        }

    }

DelegateCommand RefreshCommand to refresh ObservableCollection-bound DataGrid

copy iconCopydownload iconDownload
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
public class ViewModel
{
    public ViewModel() 
    {
        RefreshCommand = new Command(async()=> await ExecuteRefreshCommand());
        LicenceHolders = new ObservableCollection<LicenceHolder>();
    }

    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenceHolder> LicenceHolders { get; set; }

    private async Task ExecuteRefreshCommand()
    {
        if (LicenceHolders == null)
        {
            LicenceHolders = new ObservableCollection<LicenceHolder>();
        }
        LicenceHolders.Clear();

        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
    }
}
public partial class SomeView : ContentPage
{
    public SomeView(ViewModel viewModel) 
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}
public partial class SomeView : ContentPage
    {
        public SomeView() 
        {
            InitializeComponent();
            BindingContext = new ViewModel();
        }
    }
private void Button_OnClick(object sender, OnClickEventArgs e)
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
if (((ViewModel)BindingContext).RefreshCommand.CanExecute())
{
   ((ViewModel)BindingContext).RefreshCommand.Execute();
}
protected void OnLicenHoldersPropertyChanged()
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenceHolders"));
}
   public class LicenseHolder
{
    public string Name { get; set; }
}

public class ViewModel
{
    public ViewModel()
    {
        RefreshCommand = new GalaSoft.MvvmLight.CommandWpf.RelayCommand(this.ExecuteRefreshCommand);
        LicenseHolders = new ObservableCollection<LicenseHolder>();
    }
    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenseHolder> LicenseHolders { get; set; }
    private void ExecuteRefreshCommand(object o)
    {
        if (LicenseHolders == null)
        {
            LicenseHolders = new ObservableCollection<LicenseHolder>();
        }
        LicenseHolders.Clear();
        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
        LicenseHolders.Add(new LicenseHolder(){Name ="Ted"});
        LicenseHolders.Add(new LicenseHolder(){Name = "Bill"});

    }
}
<Window x:Class="WpfApp1.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"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <local:ViewModel x:Key="ViewModelAsDataSource" />
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="40"/>
    </Grid.ColumnDefinitions>
    <DataGrid Grid.Column="1" Grid.Row="1" ItemsSource="{Binding LicenseHolders }" AutoGenerateColumns="false">
        <DataGrid.Columns>
            <DataGridTextColumn Header="License Holder Name" Width="Auto" MinWidth="18" Binding="{Binding Name }" />
        </DataGrid.Columns>

    </DataGrid>

    <Button Grid.Column="1" Grid.Row="2" Content="Refresh" Command="{Binding RefreshCommand}" Width="50" Height="30"/>
     <Button Grid.Column="1" Grid.Row="3" Content="Refresh" Click="ButtonBase_OnClick" Width="50" Height="30"/>
    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        ((ViewModel)DataContext).RefreshCommand.Execute(null);
    }

}
   public class LicenseHolder
{
    public string Name { get; set; }
}

public class ViewModel
{
    public ViewModel()
    {
        RefreshCommand = new GalaSoft.MvvmLight.CommandWpf.RelayCommand(this.ExecuteRefreshCommand);
        LicenseHolders = new ObservableCollection<LicenseHolder>();
    }
    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenseHolder> LicenseHolders { get; set; }
    private void ExecuteRefreshCommand(object o)
    {
        if (LicenseHolders == null)
        {
            LicenseHolders = new ObservableCollection<LicenseHolder>();
        }
        LicenseHolders.Clear();
        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
        LicenseHolders.Add(new LicenseHolder(){Name ="Ted"});
        LicenseHolders.Add(new LicenseHolder(){Name = "Bill"});

    }
}
<Window x:Class="WpfApp1.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"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <local:ViewModel x:Key="ViewModelAsDataSource" />
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="40"/>
    </Grid.ColumnDefinitions>
    <DataGrid Grid.Column="1" Grid.Row="1" ItemsSource="{Binding LicenseHolders }" AutoGenerateColumns="false">
        <DataGrid.Columns>
            <DataGridTextColumn Header="License Holder Name" Width="Auto" MinWidth="18" Binding="{Binding Name }" />
        </DataGrid.Columns>

    </DataGrid>

    <Button Grid.Column="1" Grid.Row="2" Content="Refresh" Command="{Binding RefreshCommand}" Width="50" Height="30"/>
     <Button Grid.Column="1" Grid.Row="3" Content="Refresh" Click="ButtonBase_OnClick" Width="50" Height="30"/>
    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        ((ViewModel)DataContext).RefreshCommand.Execute(null);
    }

}
   public class LicenseHolder
{
    public string Name { get; set; }
}

public class ViewModel
{
    public ViewModel()
    {
        RefreshCommand = new GalaSoft.MvvmLight.CommandWpf.RelayCommand(this.ExecuteRefreshCommand);
        LicenseHolders = new ObservableCollection<LicenseHolder>();
    }
    public ICommand RefreshCommand { get; private set; }
    public ObservableCollection<LicenseHolder> LicenseHolders { get; set; }
    private void ExecuteRefreshCommand(object o)
    {
        if (LicenseHolders == null)
        {
            LicenseHolders = new ObservableCollection<LicenseHolder>();
        }
        LicenseHolders.Clear();
        //Code here for async retrieval of licence holder records from database 
        //and addition of new LicenceHolder instances to the LicenceHolders collection
        LicenseHolders.Add(new LicenseHolder(){Name ="Ted"});
        LicenseHolders.Add(new LicenseHolder(){Name = "Bill"});

    }
}
<Window x:Class="WpfApp1.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"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <local:ViewModel x:Key="ViewModelAsDataSource" />
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="40"/>
    </Grid.ColumnDefinitions>
    <DataGrid Grid.Column="1" Grid.Row="1" ItemsSource="{Binding LicenseHolders }" AutoGenerateColumns="false">
        <DataGrid.Columns>
            <DataGridTextColumn Header="License Holder Name" Width="Auto" MinWidth="18" Binding="{Binding Name }" />
        </DataGrid.Columns>

    </DataGrid>

    <Button Grid.Column="1" Grid.Row="2" Content="Refresh" Command="{Binding RefreshCommand}" Width="50" Height="30"/>
     <Button Grid.Column="1" Grid.Row="3" Content="Refresh" Click="ButtonBase_OnClick" Width="50" Height="30"/>
    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        ((ViewModel)DataContext).RefreshCommand.Execute(null);
    }

}

Delete selected row in DataGrid bound to an ObservableCollection

copy iconCopydownload iconDownload
<Button Content="Button">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <i:InvokeCommandAction Command="{Binding MyCommand }" 
                            CommandParameter="{Binding PassRow/IDHere}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
public class ViewModel
{
    public ICommand MyCommand { get; set; }

    public ViewModel()
    {
        MyCommand = new DelegateCommand<object>(OnRowDeleted);
    }

    public void OnRowDeleted(object o)
    {
        // remove the value from your observablecollection here using LINQ
    }
}
<Button Content="Button">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <i:InvokeCommandAction Command="{Binding MyCommand }" 
                            CommandParameter="{Binding PassRow/IDHere}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
public class ViewModel
{
    public ICommand MyCommand { get; set; }

    public ViewModel()
    {
        MyCommand = new DelegateCommand<object>(OnRowDeleted);
    }

    public void OnRowDeleted(object o)
    {
        // remove the value from your observablecollection here using LINQ
    }
}
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>
    public class LicensesViewModel : BaseInpc
    {
        // A collection-property of the ObservableCollection type is best done «ReadOnly».
        public ObservableCollection<LicenseHolders> LicensesHolders { get; }
            = new ObservableCollection<LicenseHolders>();
        public void FillDataGrid()
        {

            //---------------
            //---------------
            //---------------

                //if (licenseHolders == null)
                //    licenseHolders = new ObservableCollection<LicenseHolders>();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {

                    LicensesHolders.Add(new LicenseHolders
                    {

                        example = dr[0].ToString(),
                        // more of the same...

                    });
                }
            }
        }


        private RelayCommand _removeLicenseCommand;
        public RelayCommand RemoveLicenseCommand => _removeLicenseCommand
            ?? (_removeLicenseCommand = new RelayCommand<LicenseHolders>(RemoveLicenseExecute, RemoveLicenseCanExecute));

        private bool RemoveLicenseCanExecute(LicenseHolders license)
        {
            // Checking for the Removable License in the Collection
            return LicensesHolders.Contains(license);
        }

        private void RemoveLicenseExecute(LicenseHolders license)
        {
            // If necessary, the code for removing the license from the database is placed at the beginning of the method.
            // For example, calling some method for this, returning true if the deletion is successful.
            var result = RemoveFromBD(license);

            //It is then removed from the collection.
            if (result)
                LicensesHolders.Remove(license);
        }

        private bool RemoveFromBD(LicenseHolders license)
        {
            throw new NotImplementedException();
        }
    }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicenseCommand}"
    CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"/>
        private RelayCommand _removeLicensesCommand;
        public RelayCommand RemoveLicensesCommand => _removeLicensesCommand
            ?? (_removeLicensesCommand = new RelayCommand<IList>(RemoveLicensesExecute, RemoveLicensesCanExecute));

        private bool RemoveLicensesCanExecute(IList licenses)
        {
            // Checking for the Removable License in the Collection
            return licenses.OfType<LicenseHolders>().Any(license => LicensesHolders.Contains(license));
        }

        private void RemoveLicensesExecute(IList licenses)
        {
            foreach (var license in licenses.OfType<LicenseHolders>().ToArray())
            {
                var result = RemoveFromBD(license);

                if (result)
                    LicensesHolders.Remove(license);
            }
        }
<Button Style="{DynamicResource ButtonWithRoundCornersGreen}" 
    FontSize="22" x:Name="btnDelete" Content="Delete" 
    Width="187" Height="47" Background="#48bb88" Foreground="White" 
    Canvas.Left="547" Canvas.Top="668" IsEnabled="False"
    Command="{Binding RemoveLicensesCommand}"
    CommandParameter="{Binding SelectedItems, ElementName=dgLicenseHolder}"/>
    private RelayCommand<LicenseHolders> _removeLicenseHoldersCommand;

    public RelayCommand<LicenseHolders> RemoveLicenseHolderCommand => _removeLicenseHoldersCommand
        ?? (_removeLicenseHoldersCommand = new RelayCommand<LicenseHolders>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
public partial class Personell : Window 
{
    public Personell() => InitializeComponent();
}
<Window.DataContext>
  <local:LicenseHoldersViewModel/>
</Window.DataContext>

WPF - MVVM: how to draw a movable Rectangle with mouse

copy iconCopydownload iconDownload

  void MyCanvas_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  { 
       MyShapeCollectionViewModel.StoreMouseDown(e);
  }

  void MyCanvas_PreviewMouseMove(object sender, MouseButtonEventArgs e)
  { 
       MyShapeCollectionViewModel.ModifyShapes(e);
  }
    
  void MyCanvas_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  { 
       MyShapeCollectionViewModel.ModifyShapes(e);
  }

EF6 internal connection and transaction lifecycle issue

copy iconCopydownload iconDownload
    public class MyDbContext() : DbContext
    {
        public MyDbContext(string connectionString) : base(connectionString)
        {
           Configuration.LazyLoadingEnabled = false;
           Configuration.ProxyCreationEnabled = false;
        }
        
        public DbSet<MyEntityOne> EntityOne { get; set; }
        public DbSet<MyEntityTwo> EntityTwo { get; set; }
    }

Community Discussions

Trending Discussions on mvvmlight
  • How can I change IsInDesignMode to use it in Microsoft.Toolkit.MVVM?
  • CommandParameter not passed to CanExecute when databound within a DataGrid (CanExecute parameter is null)
  • C# JsonIgnore to basic class
  • Declaring Design-Time ViewModel for Avalonia Window
  • GalaSoft MvvmLight not disabling UserControl with RelayCommand
  • The KeyDown event will not fire, but the exact same code with PreviewMouseLeftButtonDown event will
  • DelegateCommand RefreshCommand to refresh ObservableCollection-bound DataGrid
  • Delete selected row in DataGrid bound to an ObservableCollection
  • WPF - MVVM: how to draw a movable Rectangle with mouse
  • EF6 internal connection and transaction lifecycle issue
Trending Discussions on mvvmlight

QUESTION

How can I change IsInDesignMode to use it in Microsoft.Toolkit.MVVM?

Asked 2022-Mar-27 at 12:11

This time I must be migrate MVVMLight and replace it with Microsoft.Toolkit.MVVM.

In the documentation is written there's no direct replacement for IsInDesignMode, altered or remove it.

I don't know any option to alter it, can anyone help me ?

     public MainViewModel()
     {
        //To Migrate GalaSoft there's no direct replacement for IsInDesignMode, remove
        //if (IsInDesignMode)
        //{
        //    // Code runs in Blend --> create design time data.
        //}
        //else
        //{
            // Code runs "for real"
           
            this.app = (App)Application.Current;
        //}
     }
    

ANSWER

Answered 2022-Mar-27 at 10:02

The general idea would be as follows, WPF for instance:

internal class View : Window
{
    public View()
    {
        Model.IsInDesignMode = () => DesignerProperties.GetIsInDesignMode(this);
    }

    private Model Model => DataContext as Model ?? throw new InvalidOperationException();
}

internal class Model
{
    public Func<bool> IsInDesignMode { get; set; }

    public Model()
    {
        if (IsInDesignMode is null)
            throw new InvalidOperationException();

        if (IsInDesignMode())
        {
            int i;
        }
        else
        {
            int i;
        }
    }
}

You can inject it differently, querying a platform-provided service for instance, I guess you get the point.

Source https://stackoverflow.com/questions/71634846

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install mvvmlight

More information about the MVVM Light Toolkit can be found on http://www.mvvmlight.net.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with mvvmlight
Consider Popular Form Libraries
Compare Form Libraries with Highest Support
Compare Form Libraries with Highest Quality
Compare Form Libraries with Highest Security
Compare Form Libraries with Permissive License
Compare Form Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.