Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Data Binding Architecture Question

I'm trying to learn how to use WPF binding and the MVVM architecture. I'm running into some trouble with Dependency Properties. I've tried to control the visibility of an item on the view by binding it to a DependencyProperty in the DataContext, but it doesn't work. No matter what I set the GridVisible value to in the constructor of the view model below, it is always displayed as visible when I run the code.

Can anyone see where I'm going 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)
    {
        // Do other stuff in response to the data change.
    }
}

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}}">

        <!-- Other elements in here -->

    </Grid>

</UserControl>

I've looked at several tutorials online, and it seems like I'm correctly following what I've found there. Any ideas? Thanks!

like image 412
RobotNerd Avatar asked Oct 25 '22 13:10

RobotNerd


1 Answers

Take the ElementName off your binding, that doesn't seem correct. Change it to:

<Grid x:Name="_myGrid"
        Visibility="{Binding Path=GridVisible,
            Converter={StaticResource BoolToVisConverter}}">
like image 115
thornhill Avatar answered Nov 07 '22 16:11

thornhill