Question

I have xaml button like so:

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

Code behind:

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"
}

In javascript i would just do button.getElementsByTagName("image")[0];

Was it helpful?

Solution 2

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
}

OTHER TIPS

You could assign a name to the Image control and then access it by means of the FindName method of the Button's Template:

<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;
}
    <Button Click="SyncToDeviceToggle_OnClick" Margin="0,224,0,302">
            <Button.Background>
                <ImageBrush ImageSource="Img/kin.png" x:Name="MyBrush"/>
            </Button.Background>
        </Button>

If done in this way, you can directly access MyBrush by its direct name in the .cs file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top