访问 C# 中的嵌套 XAML 控件
本文关键字:XAML 控件 嵌套 访问 | 更新日期: 2023-09-27 17:57:14
我正在创建一个应用程序,其中在 WPF 中的 ListBox 中的 DataTemplate 中有一个 TextBox 元素。我想按名称访问 TextBox 元素以进行编辑,或直接从 C# 代码中读取值,请帮助。WPF 应用程序中添加了多个文本框,那么如何按索引对这些文本框进行排序呢?
<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"。任何帮助不胜感激,谢谢你的时间。:)
您应该真正将列表框项源绑定到对象的集合并读取/更改它,而不是直接访问文本框。但是,如果由于某种原因您不能或不想这样做,则此代码可以帮助您。(请注意,我真的不鼓励这个解决方案)
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;
}