比我聪明的人可以请帮助完成一个简单的编码任务:将复选框的.ischecked绑定到对象的布尔属性?我创建了一个简单的项目来模仿我在大型项目中试图进行的操作,以进行简单的调试和演示。我有一个复选框,单击该复选框可设置类对象的布尔属性。 UI上的另一个复选框应基于该布尔属性的T / F值更新其检查状态。这里有什么问题,如何解决并使其正常工作?我“相信”该问题可能是因为我设置的对象的属性不同于checkbox.ischecked属性绑定到(???)的对象的属性。那是问题所在,如果是的话,我该如何解决? VB或XAML方面需要实现哪些代码?
MainWindow.xaml.vb
Public Bools As New Boolean_Properties
Private Sub ckbx1_Click(sender As Object, e As RoutedEventArgs) Handles ckbx1.Click
If ckbx1.IsChecked Then
Bools.Sta1Mode = True
Else Bools.Sta1Mode = False
End If
End Sub
Boolean_Properties类
Implements INotifyPropertyChanged
Private ModeSta1 As Boolean
Public Event ThePropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Property Sta1Mode As Boolean
Get
Return ModeSta1
End Get
Set(ByVal value As Boolean)
ModeSta1 = value
RaiseEvent ThePropertyChanged(Me, New PropertyChangedEventArgs("Sta1Mode"))
End Set
End Property
XAML
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindBooleanProperty"
mc:Ignorable="d"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="MainWindow" Height="217.032" Width="226.067">
<Window.DataContext>
<local:Boolean_Properties/>
</Window.DataContext>
<Grid>
<CheckBox Content="Output" HorizontalAlignment="Left" Margin="99.866,134.399,0,0" VerticalAlignment="Top" IsChecked="{Binding Sta1Mode, Mode=OneWay}">
<CheckBox.DataContext>
<local:Boolean_Properties/>
</CheckBox.DataContext>
</CheckBox>
<CheckBox x:Name="ckbx1" Content=" Input" HorizontalAlignment="Left" Margin="99.866,78.932,0,0" VerticalAlignment="Top"/>
</Grid>
答案 0 :(得分:1)
您可以使用WPF数据绑定:
无需使用if
进行更改,只需绑定XAML接口并更改类的属性即可。
Imports System.ComponentModel
Public Class Class1
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private _ModeSta1 As Boolean
Property ModeSta1 As Boolean
Get
Return _ModeSta1
End Get
Set(ByVal value As Boolean)
_ModeSta1 = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(ModeSta1)))
End Set
End Property
End Class
将CheckBox更改为仅绑定到ModeSta1
属性
<CheckBox x:Name="ckbx1"
Content=" Input"
Margin="99.866,78.932,0,0"
VerticalAlignment="Top"
HorizontalAlignment="Left"
IsChecked="{Binding Path=ModeSta1, Mode=TwoWay}"
/>
更改ModeSta1
的值时,将更新用户界面,如果用户单击复选框,则ModeSta1
的值也将更改。
Dim c = New Class1
DataContext = c
' You can change the property and this change will be visible on the UI
c.ModeSta1 = True