我有一个数据集,我在创建表单实例时创建运行时(能够拥有该数据集的多个实例)。在此表单上有几个文本框,其中包含数据集的数据绑定。
某些值需要在文本框中显示不同,然后如何在数据集中存储(用户必须能够更改文本框中的值,并因此更新数据集中的值)。
我创建了一个实现IValueConverter的转换器类(经过几个小时的查看,我发现我还需要在PresentationFramework.dll中引用PresentationFramework),但现在我确实有一个转换器。
但是如何告诉我的数据绑定使用转换器?
创建表单的一些代码:
Public Sub Init()
Dim data As DataSet
Dim tblTest As DataTable
'create data structure
data = New DataSet("MyData")
tblTest = New DataTable("Test")
tblTest.Columns.Add("test1")
tblTest.Columns.Add("test2")
tblTest.Columns.Add("test3")
data.Tables.Add(tblTest)
'Bind datastructure
txtTest1.DataBindings.Add("text", data, "MyData.test1")
txtTest2.DataBindings.Add("text", data, "MyData.test2")
txtTest3.DataBindings.Add("text", data, "MyData.test3")
End Sub
我的IDataConverter代码:
Public Class MyValueConverter
Implements System.Windows.Data.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
Return "X" & value
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 value & "Y"
End Function
End Class
(它只是添加X或Y用于调试目的并了解它是如何工作的)
有人知道如何告诉它在VB.Net(VS2010)中使用我的转换器吗?请注意我的绑定是在运行时创建的,所以我没有xaml绑定到hack into ...
答案 0 :(得分:0)
Binding类有一个Format和Parse事件来处理你的情况:
Private WithEvents TextBinding As Binding
Public Sub New()
InitializeComponent()
TextBinding = New Binding("Text", data.Tables("Test"), "test1")
TextBox1.DataBindings.Add(TextBinding)
End Sub
Private Sub TextBinding_Format(sender As Object, e As ConvertEventArgs) _
Handles TextBinding.Format
e.Value = "X" & e.Value
End Sub
Private Sub TextBinding_Parse(sender As Object, e As ConvertEventArgs) _
Handles TextBinding.Parse
If e.Value IsNot Nothing AndAlso e.Value.ToString.Length > 0 Then
e.Value = e.Value.ToString.Substring(1)
End If
End Sub