【发布时间】:2013-11-27 11:19:34
【问题描述】:
在我的 Windows Phone 8 应用程序中,我有一个 ListBox 控件。此列表框包含一个网格,其中包含一对 TextBlock(字段的标题)和一个 TextBox(用户输入)控件。此列表是根据应用程序连接到的服务的结果生成的。我需要做的是访问列表中的每个文本框,并带回它的值。为此,我将每个项目的唯一 ID 绑定到 TextBox 的 Tag 属性,并且我正在使用 LostFocus 事件来捕获用户输入。一旦这被捕获并添加到后面代码中的集合中,当用户单击列表下的按钮时,数据就会被处理。这适用于除最后一项之外的每一项。
问题是如果单击按钮,LostFocus 将不起作用。按钮单击方法似乎优先于文本框 LostFocus 方法。因此,如果列表中只有 1 项,则不会记录该值。代码如下:
<ItemsControl x:Name="itmScreen4">
<TextBlock Margin="0,10,0,10">Fields</TextBlock>
<ListBox x:Name="lstCustom" ItemsSource="{Binding}" Visibility="Visible">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="grdCustom">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" x:Name="txtCustTitle" Text="{Binding Name}" Foreground="#4C4C4C" FontSize="18" Margin="0,15,0,0"></TextBlock>
<TextBox Tag="{Binding DataID}" x:Name="txtCust" Grid.Row="1" Style="{StaticResource TextBox}" Width="450" LostFocus="txtCust_LostFocus"></TextBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="btnSubmit" Content="Submit" Background="#404040"></Button>
</ItemsControl>
对于列表中的最后一项(或者如果列表中只有一项),调用 btnSubmit 方法时不会调用 txtCust_LostFocus 方法。关于如何捕获最终文本框值的任何想法?
我尝试了一些其他方法(例如,投射 ListBoxItem 并在其上执行 FindName),但没有找到任何可行的方法。谷歌也没有太多帮助。提前致谢。
编辑:
这是后面的代码。我正在将自定义类绑定到如下列表。
此处的类定义(出于可读性目的,我删除了一些属性):
Public Class CustomDataRequest
Public Sub New()
End Sub
Public Property ID As Integer
Public Property Name As String
End Class
在此处的代码中使用:
Public Sub ShowCustomData()
Dim CustomDataList As New List(Of CustomDataRequest)()
For Each item In _CustomDataRequestList
If item.ID= _CurrentID Then
CustomDataList.Add(item)
End If
Next
lstCustom.ItemsSource = CustomDataList.ToArray
End Sub
txtCust_LostFocus 方法只是捕捉瞬间的字段。一旦我可以真正调用它,我就可以将数据添加到集合中:
Private Sub txtCust_LostFocus(sender As Object, e As RoutedEventArgs)
Dim elem = DirectCast(sender, FrameworkElement)
Dim txt = DirectCast(elem.FindName("txtCust"), TextBox)
Dim text As String = txt.Text
Dim tag As String = txt.Tag
End Sub
问题是一旦按钮被点击,它就永远不会被调用:
Protected Sub btnSubmit_Tap(sender As Object, e As Input.GestureEventArgs) Handles btnSubmit.Tap
ValidateData()
End Sub
【问题讨论】:
-
也许你可以在后面添加你的代码。这将使您更容易掌握您在做什么。接下来,为什么不将
TextBox的Text属性绑定到用于绑定Name和DataId的类的属性? -
感谢您的回复。我添加了一些代码来显示我在做什么。您能否详细说明您将文本框中的文本绑定到属性的建议?我不确定它会有什么帮助,因为仍然不会调用 LostFocus 方法。
-
你应该在
CustomDataRequest类中添加一个属性,例如SomeText然后通过在 xamlText="{Binding SomeText, Mode=TwoWay}"中添加此属性将TextBox绑定到此属性。当用户在文本框中添加文本时,绑定会将该文本放入您的属性中。您不再需要LostFocus处理程序。 -
我按照你说的做了,文本确实绑定到类,这是 lees 代码,所以谢谢你。但是,问题仍然存在,是一种时尚。如果在点击按钮时选择了文本框,即用户在框中输入了文本但在单击框之前点击了按钮,则文本不会被绑定。按钮单击事件仍然优先于其他所有事件。有任何想法吗...?谢谢
-
哦,是的,我忘了。由于您的文本框不会失去焦点,因此绑定源(SomeText)不会更新。你可以解决它。看看这个问题的答案:stackoverflow.com/questions/4833100/…
标签: vb.net xaml windows-phone-8 textbox listbox