WPF数据绑定转换器
本文关键字:转换器 数据绑定 WPF | 更新日期: 2023-09-27 18:05:04
我有一个按钮,我基本上要显示或隐藏它的基础上,如果某个字符串有一个值或没有。我在代码中创建按钮,所以我试图使用转换器的数据绑定,但我似乎无法在值变化后获得绑定上的转换器。我不确定我做得对不对……这是我为创建按钮和绑定和转换器。"sFileLocation"是我的类"QuestionsFile"中的字符串。这适用于初始化,但它只是当字符串的值发生变化时,这个绑定不会看到变化,也不会为我运行转换器和所有这些…谢谢你的帮助。
Dim btn2 As New Button
Dim b2 As New Binding("sFileLocation")
b2.Mode = BindingMode.TwoWay
b2.Source = DirectCast(q, QuestionListClass.QuestionsFile)
b2.Converter = New ViewButtonConverter
b2.ConverterParameter = b2.Source
btn2.SetBinding(Button.VisibilityProperty, b2)
<ValueConversion(GetType(String), GetType(Visibility))> _
Public Class ViewButtonConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
Dim result As Visibility = Visibility.Collapsed
If parameter IsNot Nothing Then
If parameter.GetType Is GetType(String) Then
If DirectCast(parameter, String) <> "" Then
result = Visibility.Visible
Else
result = Visibility.Collapsed
End If
End If
End If
Return result
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Return Nothing
End Function
End Class
'this how my class is set up now, its enormous or else id post all of it..
Public Class QuestionListClass
Public Class QuestionList
Inherits ObservableCollection(Of QuestionType)
End Class
End Class
我也不明白的是,如果我只是将属性绑定到Button.Content,那么绑定工作得很好。因此,当属性被更改时,属性会正确更新,按钮的内容也会相应更改。
没有看到你的代码的其余部分听起来像你的ViewModel或无论你绑定到没有实现INotifyPropertyChanged
还有,为什么在代码后端而不是在XAML中进行绑定?将可见性转换器定义为资源后:
<ViewButtonConverter x:Key="VisibilityConverter" />
你可以在下面使用它:
<Button x:Name="button" Content="Click Me" Visibility="{Binding Path=sFileLocation, Converter={StaticResource VisibilityConverter}}" />
你的字符串所在的类需要实现INotifyPropertyChanged: Implements INotifyPropertyChanged
,然后setter需要通知世界它已经改变了…
参见MSDN获取更多信息,但这里是他们示例中的代码片段:
Public Property CustomerName() As String
Get
Return Me.customerNameValue
End Get
Set(ByVal value As String)
If Not (value = customerNameValue) Then
Me.customerNameValue = value
NotifyPropertyChanged("CustomerName")
End If
End Set
End Property
我遇到的问题是设置转换器参数。一旦我摆脱了它,它就像预期的那样工作了。我很感激你所有的帮助,以下是对我有用的。
Dim b2 As New Binding("sFileLocation")
b2.Mode = BindingMode.TwoWay
b2.Source = DirectCast(q, QuestionListClass.QuestionsFile)
b2.Converter = New ViewButtonConverter
btn2.SetBinding(Button.VisibilityProperty, b2)