我正在创建一个应用程序,在DataTemplate中,在WPF的ListBox中有一个TextBox元素。我想按名称访问TextBox元素以便编辑,或直接从C#代码中读取值,请帮忙。在WPF应用程序中添加了多个TextBox,因此我如何按索引对它们进行排序?
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="336" Margin="276,69,0,0" VerticalAlignment="Top" Width="242" SelectionChanged="listBox_SelectionChanged">
Grid.IsSharedSizeScope="True"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate x:Name="D_Template">
<Grid Margin="4" Width="222">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox x:Name ="TextValue" Grid.Column="1" Text="{Binding Value}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如您所见,ListBox的变量名称为“listBox”,DataTemplate已分配给“D_Template”,TextBox分配给名称“TextValue”。感谢您的帮助,谢谢您的时间。 :)
答案 0 :(得分:0)
你应该将listbox itemssource绑定到一个对象集合并读取/更改它而不是直接访问文本框。但是如果由于某种原因你不能或不想这样做,这段代码可以帮到你。 (请注意,我真的不鼓励这个解决方案)
private void Button_Click(object sender, RoutedEventArgs e)
{ //pretend you want to access the second item
object myItem = myListbox.Items[1];
ListBoxItem container = myListbox.ItemContainerGenerator.ContainerFromItem(myItem) as ListBoxItem;
ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(container);
DataTemplate myDataTemplate = contentPresenter.ContentTemplate;
TextBox myTextbox = myDataTemplate.FindName("myTextbox", contentPresenter)as TextBox;
if (myTextbox != null)
{
myTextbox.Text = "text changed!";
}
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
public static childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
foreach (childItem child in FindVisualChildren<childItem>(obj))
{
return child;
}
return null;
}