x:Name探訪(その2) UserControl の x:Name を FindName

Silveright 3 の VS テンプレートから最初に表示される画面の名前が Page から MainPage に変わりましたね。いい感じです。


今日はこの MainPage の中に別に作った UserControl を配置して、その中のエレメントを FindName 出来るかどうかです。Silverlight 2 では MainPage(Page)のインスタンスからは出来なくって、 UserControl のインスタンスでは見つけられたと記憶してます。


以下のような UserControl を作ります。

<UserControl x:Class="XNameResearch1.SilverlightControl1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  Width="200" Height="200">
  <Grid x:Name="LayoutRoot" Background="Red">
    <Rectangle Fill="Blue" x:Name="BlueRectangle" />
  </Grid>
</UserControl>

こいつを MainPage に配置します。

<UserControl x:Class="XNameResearch1.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  xmlns:local="clr-namespace:XNameResearch1"
  Width="400" Height="300">
  <StackPanel x:Name="LayoutRoot" Background="Red">
    <Button Click="Button_Click" Content="Click Me!" />
    <local:SilverlightControl1 x:Name="UserControl" />
  </StackPanel>
</UserControl>

ボタンのクリックイベントで FindName して取得できるかチェックしてみます。まずは MainPage のインスタンスのFindName で取得してみます。

private void Button_Click(object sender, RoutedEventArgs e) {
  object blueRectangle = this.FindName("BlueRectangle");
  MessageBox.Show(blueRectangle == null ? "Not found..." : "Found !");
}

見つかりませんでした。。。


次に UserControl のインスタンスから FindName してみます。

private void Button_Click(object sender, RoutedEventArgs e) {
  object blueRectangle = UserControl.FindName("BlueRectangle");
  MessageBox.Show(blueRectangle == null ? "Not found..." : "Found !");
}

見つかりました。