我有一个列表框(下方),其中有2个TextBox,数据库中的数据在文本框中显示正常。但是我希望能够将值保存到数据库中,因为在用户输入其名称之前,文本框一直是空白的。
由于文本框位于列表框中,我认为我必须找到文本框的名称才能访问Text =“name”以保存到数据库。
我尝试使用可视化树助手,但我无法让它工作。视觉树帮助者是正确的方法吗?
<ListBox HorizontalAlignment="Left" Margin="0,20,0,0" x:Name="lst_userProfiles" VerticalAlignment="Top" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" x:Name="stk_container">
<!-- FIRST NAME-->
<TextBlock Text="First Name: " FontSize="22" />
<TextBox Text="{Binding UP_firstName, Mode=TwoWay}" Width="400" x:Name="txt_firstName" />
<!-- LAST NAME -->
<TextBlock Text="Surname: " FontSize="22" />
<TextBox Text="{Binding UP_lastName, Mode=TwoWay}" Width="400" x:Name="txt_surname" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
背后的代码
private void btn_save_Click(object sender, RoutedEventArgs e)
{
//first name
ListBoxItem _firstName = this.lst_userProfiles.ItemContainerGenerator.ContainerFromItem("txt_firstName") as ListBoxItem;
TextBox firstName = FindFirstElementInVisualTree<TextBox>(_firstName);
string getFirstName = Convert.ToString(firstName);
//lst name
ListBoxItem _lasyName = this.lst_userProfiles.ItemContainerGenerator.ContainerFromItem("txt_surname") as ListBoxItem;
TextBox lastName = FindFirstElementInVisualTree<TextBox>(_lasyName);
string getLastName = Convert.ToString(lastName);
Service1Client svc = new Service1Client();
svc.AddProfileCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(svc_AddProfileCompleted);
svc.AddProfileAsync(loginID, getFirstName, getLastName);
}
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
for (int i = 0; i < count; i++){
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T) {
return (T)child;
}
else {
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
答案 0 :(得分:0)
我真的不明白为什么你这样做,但你可以试试这段代码。
List<string> name = new List<string>();
int i = 0;
foreach(ListPickerItem lpi in lst_userProfiles.Items )
{
foreach(TextBox tb in (lpi.Content as StackPanel).Children)
{
name[i++] = tb.Name;
}
}