I have really simple code but it does not work.
I have a command :
public class SetYesCommand : ICommand , INotifyPropertyChanged
{
public event EventHandler CanExecuteChanged;
public event PropertyChangedEventHandler PropertyChanged;
ViewModelBase view = new ViewModelBase();
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
view.Sname = "Yes";
MessageBox.Show("Command works");
onpropertychanged("Sname");
}
private void onpropertychanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
}
}
and it is my base view model class :
public class ViewModelBase : INotifyPropertyChanged
{
private string _s;
public string Sname {
get { return _s; }
set { _s = value;
onPropertyChanged("Sname");
}
}
private void onPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
and this is my XAML code :
<Window x:Class="Test.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:Test"
mc:Ignorable="d"
xmlns:viewmodel="clr-namespace:Test.ViewModel"
xmlns:commands="clr-namespace:Test.ViewModel.Commands"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<viewmodel:ViewModelBase x:Key="base" ></viewmodel:ViewModelBase>
<viewmodel:Converters x:Key="convert" ></viewmodel:Converters>
<commands:SetYesCommand x:Key="setyes"/>
</Window.Resources>
<StackPanel>
<Button Width="100" Height="30" Command="{StaticResource setyes}"/>
<TextBox DataContext="{StaticResource base}" Text="{Binding Sname , Mode=TwoWay}"/>
<CheckBox DataContext="{StaticResource base}" IsChecked="{Binding Sname , Mode=TwoWay , Converter={StaticResource convert}}" />
<TextBox />
</StackPanel>
</Window>
As you can see simply I bound two element in my UI to a string property in my view model base class and I defiend a command for my button in UI. The command works because as you see I check it with a messagebox but the value of two other element ( textbox and checkbox) in my UI do not change.