I want to change value of ViewModel
property (which is binded with DataContext
). Extremely easy with classic Events, with Commands it becomes formidable task. This is my code:
public partial class MainWindow : Window { ViewModel _vm = new ViewModel(); public MainWindow() { InitializeComponent(); _vm.BtnClick = new BtnClick(); DataContext = _vm; } } public class BtnClick : ICommand { public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { Debug.WriteLine(parameter.ToString()); } } public class ViewModel { public ICommand BtnClick { get; set; } public string Input { get; set; } public string Output { get; set; } }
<StackPanel>
<TextBox Text="{Binding Input}"></TextBox>
<TextBlock Text="{Binding Output}"></TextBlock>
<Button Command="{Binding Path=BtnClick}" CommandParameter="{Binding Input}">Translate</Button>
</StackPanel>
Command properly takes value from TextBox
, now i want to do things with this value and save it to Output
. And problem is from Command perspective i cannot access both DataContext
and ViewModel
.
TextBlock
Text
, i have to accessViewModel
. There is no other way. – AdmiralCat3INotifyPropertyChanged
though. – Peregrine