【问题标题】:Binding CheckBox IsChecked to Stackpanel Visibility将 CheckBox IsChecked 绑定到 Stackpanel 可见性
【发布时间】:2016-06-07 03:11:28
【问题描述】:

我正在尝试使用 MVVM 将堆栈面板中某些文本框的 Visibility 属性绑定到 WPF 中复选框的 IsChecked 属性。为此,我创建了一个属性 IsBoxChecked 作为布尔值,其中包含文本框和复选框都绑定到的私有支持字段 _isBoxChecked。当我运行程序时,具有绑定 Visibility 属性的文本框会自动折叠,无论我将属性初始化为什么值。此外,如果我在构造函数中将属性初始化为 true,则不会显示复选框。这是代码。

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

这是我的 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

绑定到属性的复选框可以正常运行。如果我在设置器上为 IsBox Checked 属性设置断点,那么如果我选中或取消选中该框,调试器就会中断。

感谢您的帮助。

乔恩

【问题讨论】:

    标签: wpf vb.net checkbox mvvm data-binding


    【解决方案1】:

    不确定VB语法,但不应该这样

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

    改成

    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))
    

    这可以解释为什么没有通知。传递参数而不是常量字符串

    您也可以直接将 TextBlock Visibility 绑定到 IsChecked 属性(通过 ElementName 引用 CheckBox)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2010-12-06
      • 2016-04-26
      • 2012-11-15
      • 2011-02-24
      • 1970-01-01
      相关资源
      最近更新 更多