Basic click event implementation for a Button control.
private void MyButton_Click(object sender, RoutedEventArgs e)
{
// TODO: Add your code here
MessageBox.Show("Button clicked!");
}
Binding a TextBox to a property in the ViewModel.
<TextBox Text="{Binding Path=UserName, UpdateSourceTrigger=PropertyChanged}" />
Using ObservableCollection to auto-update UI lists.
public ObservableCollection<string> Items { get; set; } = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
DataContext = this;
Items.Add("Item 1");
Items.Add("Item 2");
}
Simple ICommand implementation for MVVM commands.
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;
public void Execute(object parameter) => _execute(parameter);
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
Merge multiple resource dictionaries in App.xaml.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Light.xaml" />
<ResourceDictionary Source="Styles/Controls.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>