Reputation: 183
Update: Full working example:
I am using property binding to change the visibility of an usercontrol in my window. With the INotifyPropertyChanged i notify the UI to update.
I am using this RelayCommand implementation.
C#
//ViewModel:
public class homeViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Visibility _Home;
public Visibility Home
{
get { return _Home; }
set {
if(_Home == value) return;
_Home = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Home"));
}
}
public ICommand HideHomeCommand
{
get {
return new RelayCommand(
o => HideUserControl,
o => {return Home != Visibility.Collapsed;}
);
}
}
private void HideUserControl()
{
Home = Visibility.Collapse;
}
public ICommand ShowHomeCommand
{
get {
return new RelayCommand(
o => ShowUserControl,
o => {return Home != Visibility.Visible;}
);
}
}
private void ShowUserControl()
{
Home = Visibility.Visible;
}
}
XAML:
<Window ... >
<Window.DataContext>
<vm:homeViewModel />
</Window.DataContext>
<StackPanel>
<Button Content="Show Home" Command="{Binding ShowHomeCommand}" />
<Button Content="Collapse Home" Command="{Binding HideHomeCommand}" />
<views:home Visibility="{Binding Home }" />
<!-- home is an usercontrol -->
</StackPanel>
</Window>
Upvotes: 0
Views: 453
Reputation: 3315
Since you bind visibility Home
with <views:home Visibility="{Binding Home}"/>
you should use:
PropertyChanged(this, new PropertyChangedEventArgs("Home"));
This way you invoke property changed event for Home
property. Also there is no need for _myHome
to be a property. It should be a simple private field.
There is a library called PropertyChanged.Fody which handles all these property changed events automatically, you may want to look at it.
If you want to handle PropertyChanged
events manually and you are using C# 6.0 (Visual Studio 2015), you may want to use:
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Home)));
.
With previous code if you rename Home
property and forget to change the string in PropertyChanged
event it will silently fail to notify. But with this code the compilation will fail and you will have to fix it.
Upvotes: 2