動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
C++ BuilderでのFindComponent()に相当する処理を試す。
link
code
MainWindow.xaml
<Window x:Class="_171110_t1630_findcomponent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:_171110_t1630_findcomponent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<Button Content="Button" Height="30" Click="Button_Click"/>
<TextBlock Name="T_info" Height="30"/>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _171110_t1630_findcomponent
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
object obj = FindName("T_info");
if (obj != null)
{
var txt = (TextBlock)obj;
txt.Text = "Pushed";
}
}
}
}
関連
https://stackoverflow.com/questions/12238599/find-wpf-control-by-name
においてはFindName以外にもcontrolsにDictionary登録をしておいて、あとで名前をキーとして使う例がある。
(TextBlockの場合は、FrameworkElementでなく、TextBlockでDictionaryを作る)。