从代码获取对静态资源的子控件 [英] Get child control of Static Resource from code
本文介绍了从代码获取对静态资源的子控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
例如,我有以下XAML
Hi guys,
For example I have the following XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Grid x:Key="testResource">
<TextBox Name="txtTest" Text="test"></TextBox>
</Grid>
</Window.Resources>
<Grid>
<Frame Height="100" VerticalAlignment="Top" Content="{Binding Source={StaticResource ResourceKey=testResource}}" />
<Button Height="20" Name="btnTest" Content="Test" Click="btnTest_Click" />
</Grid>
</Window>
我知道如何获取Grid x:Key="testResource"
:
I know how to get Grid x:Key="testResource"
:
Grid grid = this.FindResource("testResource") as Grid;
但是如何找到txtTest
控件?
我只发现了这样的东西:
But how can I find txtTest
control?
I figured out only something like this:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnTest_Click(object sender, RoutedEventArgs e)
{
Grid grid = this.FindResource("testResource") as Grid;
foreach (UIElement item in grid.Children)
{
if (item as TextBox != null)
{
MessageBox.Show((item as TextBox).Text);
}
}
}
}
}
有什么正确的方法吗? grid.FindName("txtTest")
不起作用.
is there any right method to do it? grid.FindName("txtTest")
doesn''t work.
推荐答案
您好,您可以按这样的名称查找它;
Hi, you can look it up by name like this;
Grid grid = this.FindResource("testResource") as Grid;
var myTextBox = grid.Children.Cast<UIElement>().
Where(el => ((string)el.GetValue(FrameworkElement.NameProperty)) == "txtTest").SingleOrDefault();
希望这会有所帮助,
弗雷德里克(Fredrik)
Hope this helps,
Fredrik
这篇关于从代码获取对静态资源的子控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文