按类型在XAML中获取子元素

时间:2014-05-14 07:17:18

标签: c# wpf xaml

我有像这样的xaml按钮:

      <Button Click="SyncToDeviceToggle_OnClick">
                            <Button.Template>
                                <ControlTemplate>
                                    <Image Source="Img/kin.png" Height="25"/>
                                </ControlTemplate>
                            </Button.Template>
                        </Button>

代码背后:

private void SyncToDeviceToggle_OnClick(object sender, RoutedEventArgs e)
{
    var image = ??//I want to get the child image element in the button without having to search for it by name specified in name="something"
}

在javascript中我会这样做      button.getElementsByTagName( “图像”)[0];

3 个答案:

答案 0 :(得分:1)

您可以为Image控件指定一个名称,然后通过Button Template的{​​{3}}方法访问它:

<ControlTemplate>
    <Image x:Name="image" Source="Img/kin.png" Height="25"/>
</ControlTemplate>

...

private void Button_Click(object sender, RoutedEventArgs e)
{
    var control = (Control)sender;
    var image = control.Template.FindName("image", control) as Image;
}

答案 1 :(得分:0)

private void Button_Click(object sender, RoutedEventArgs e)
{
        Button button = sender as Button;
        DependencyObject child = VisualTreeHelper.GetChild(button, 0);
        Image image = child as Image;
        //Now you can access your image Properties
}

答案 2 :(得分:0)

    <Button Click="SyncToDeviceToggle_OnClick" Margin="0,224,0,302">
            <Button.Background>
                <ImageBrush ImageSource="Img/kin.png" x:Name="MyBrush"/>
            </Button.Background>
        </Button>

如果以这种方式完成,您可以直接通过.cs文件中的直接名称访问MyBrush。