1
votes

I am trying to bind the Visibility property of some textboxes in a stackpanel to the IsChecked property of a checkbox in WPF using MVVM. To do so, I have created a property, IsBoxChecked as a boolean with a private backing field _isBoxChecked which both the textboxes and and checkbox are bound to. When I run the program, the textboxes that have a bound Visibility property are automatically collapsed, regardless of what value I initialize the property to. Also, the checkboxes do not show up checked if I initialize the property to true in the constructor. Here is the code.

        <StackPanel Grid.Column="0" 
                Margin="10,37" 
                HorizontalAlignment="Right" 
                VerticalAlignment="Top">
        <TextBlock Text="Always Visible" Margin="5"/>
        <TextBlock Text="Also Always Visible" Margin="5"/>
        <TextBlock Text="Needs to Hide and Unhide" Margin="5" Visibility="{Binding IsBoxChecked, Converter={StaticResource BoolToVis}}"/>
        <CheckBox Content="Text" IsChecked="{Binding IsBoxChecked, Mode=TwoWay}" Margin="5"/>

    </StackPanel>

Here is my ViewModel.

Public Class NewSpringViewModel
Implements INotifyPropertyChanged

Private _newWindow As NewView
Private _isBoxChecked As Boolean

Public Sub New()

    _newWindow = New NewView
    _newWindow.DataContext = Me
    _newWindow.Show()

    IsBoxChecked = True

End Sub

Public Property IsBoxChecked As Boolean
    Get
        Return _isBoxChecked
    End Get
    Set(value As Boolean)
        _isBoxChecked = value
        OnPropertyChanged("IsBoxChecked")
    End Set
End Property

Private Sub OnPropertyChanged(PropertyName As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("PropertyName"))
End Sub

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
End Class

The checkbox binding to the property works fine it is running. If I set a break point on the setter for the IsBox Checked property, the debugger interrupts if I check or uncheck the box.

Thanks for any help.

Jon

1

1 Answers

1
votes

not sure about VB syntax, but should not this

RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("PropertyName"))

be changed to

RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))

that would explains why there is no notifications. Pass parameter instead of a constant string

also you can directly bind TextBlock Visibility to IsChecked property (reference CheckBox by ElementName)

<StackPanel Grid.Column="0" 
        Margin="10,37" 
        HorizontalAlignment="Right" 
        VerticalAlignment="Top">
    <TextBlock Text="Always Visible" Margin="5"/>
    <TextBlock Text="Also Always Visible" Margin="5"/>
    <TextBlock Text="Needs to Hide and Unhide" Margin="5" 
               Visibility="{Binding IsChecked, ElementName=chk, Converter={StaticResource BoolToVis}}"/>
    <CheckBox Content="Text" Name="chk" Margin="5"/>
</StackPanel>