我有一个按钮,我基本上想根据某个字符串是否有值来显示或隐藏它。我在代码中创建按钮,所以我试图使用转换器的数据绑定,但我似乎无法在值更改后获取绑定转换器。我不确定我是否正确地追求这一点......这就是我创建按钮,绑定和转换器的原因。 “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,绑定工作正常。因此,属性在更改时正确更新,按钮内容也会相应更改。
答案 0 :(得分:2)
在没有看到代码的其余部分的情况下,它听起来像您的ViewModel或您绑定到的任何地方都没有实现INotifyPropertyChanged。
此外,您是否有任何理由在代码隐藏中绑定而不是在XAML中绑定?将Visibility Converter定义为资源后:
<ViewButtonConverter x:Key="VisibilityConverter" />
您可以在以下内容中使用它:
<Button x:Name="button" Content="Click Me" Visibility="{Binding Path=sFileLocation, Converter={StaticResource VisibilityConverter}}" />
答案 1 :(得分:0)
你的字符串所在的类需要实现INotifyPropertyChanged:Implements INotifyPropertyChanged
然后setter需要通知世界它已经改变了......
see MSDN for more info,但这是他们示例中的代码段:
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
答案 2 :(得分:0)
我遇到的问题是设置转换器参数。一旦我摆脱了它,它按预期工作。我感谢你的所有帮助,以及对我有用的东西。
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)