I am trying to learn how to use WPF binding and MVVM architecture. I am having problems with Dependency Properties. I tried to control the visibility of the element in the view by binding it to DependencyProperty in the DataContext, but it does not work. No matter what I set the value GridVisiblein the constructor of the view model below, it is always displayed as visible when I run the code.
Can anyone see where I'm wrong?
C # code (ViewModel):
public class MyViewModel : DependencyObject
{
public MyViewModel ()
{
GridVisible = false;
}
public static readonly DependencyProperty GridVisibleProperty =
DependencyProperty.Register(
"GridVisible",
typeof(bool),
typeof(MyViewModel),
new PropertyMetadata(false,
new PropertyChangedCallback(GridVisibleChangedCallback)));
public bool GridVisible
{
get { return (bool)GetValue(GridVisibleProperty); }
set { SetValue(GridVisibleProperty, value); }
}
protected static void GridVisibleChangedCallback(
DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
}
}
XAML Code (View):
<UserControl ... >
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter" />
</UserControl.Resources>
<UserControl.DataContext>
<local:MyViewModel x:Name="myViewModel" />
</UserControl.DataContext>
<Grid x:Name="_myGrid"
Visibility="{Binding Path=GridVisible,
ElementName=myViewModel,
Converter={StaticResource BoolToVisConverter}}">
</Grid>
</UserControl>
I looked through a few tutorials online, and it seems to me that I am correctly following what I found there. Any ideas? Thank!