我有一个VB.NET WPF应用程序,它以两种不同的模式运行(分别是设计模式和评估模式)。我添加了一个菜单选项和切换按钮,以便用户可以轻松选择他/她正在使用的模式。当然,整个应用程序的行为也取决于它是否处于设计模式,因此有必要创建一个类级布尔来表示在设计模式下工作,并将这些项IsChecked
属性绑定到它
首先,我尝试在代码隐藏中添加绑定,如下所示:
Class MainWindow
Private IsInDesignMode As Boolean = True
Private Sub Window_Loaded(sender as Object, e as RoutedEventArgs)
SetUpDataBindings()
End Sub
Private Sub SetUpDataBindings()
tglDesignMode.IsChecked = New Binding(IsInDesignMode)
mnuDesignMode.IsChecked = New Binding(IsInDesignMode)
End Sub
End Class
然后我读到控件只能绑定到属性,并且我读到的所有示例都显示了公共属性,所以我将上面的第2行更改为:
Public Property IsInDesignMode as Boolean = True
但是在这两种情况下,启动时都没有检查按钮和菜单,并且没有一起检查/取消选中。所以我尝试了一种不同的策略,使用XAML:
<ToggleButton Name="tbnDesignMode"
IsChecked="{Binding IsInDesignMode}">
DESIGN MODE
</ToggleButton>
那也没有用。我做了更多的研究,发现有些人在他们的XAML中使用ElementName
和Path
。所以我尝试了以下内容:
<MenuItem Name="mnuDesignMode"
Header="_Design Mode"
IsCheckable="True"
IsChecked="{Binding ElementName=mnuDesignMode, Path=IsInDesignMode}"/>
那也没有用。我也看到一些人使用自定义转换器,但他们没有解释转换器正在做什么(从C#到VB的转换也没有帮助)。
长话短说,有人可以帮我设置从这些控件的IsChecked
属性到类级布尔值的绑定,并解释原因和方法吗?
答案 0 :(得分:0)
请参阅以下代码。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<StackPanel>
<ToggleButton Name="tbnDesignMode"
IsChecked="{Binding Path=IsInDesignMode,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}">
DESIGN MODE
</ToggleButton>
<MenuItem Name="mnuDesignMode"
Header="_Design Mode"
IsCheckable="True"
IsChecked="{Binding Path=IsInDesignMode,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}"/>
</StackPanel>
Imports System.ComponentModel
Class MainWindow
Implements INotifyPropertyChanged
Private isInDesignModeValue As Boolean
Public Property IsInDesignMode() As Boolean
Get
Return isInDesignModeValue
End Get
Set(ByVal value As Boolean)
isInDesignModeValue = value
OnPropertyChanged1("IsInDesignMode")
End Set
End Property
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
IsInDesignMode = True
End Sub
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged1(ByVal name As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
End Class
但我建议你寻找MVVM方法而不是代码。