Reputation: 757
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];
Upvotes: 0
Views: 4402
Reputation: 222722
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
}
Upvotes: 0
Reputation: 2283
<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.
Upvotes: -1
Reputation: 128146
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;
}
Upvotes: 2