0

I'm a newby in WPF, so please exuse if this is a trivial question...

I need to create many similar controls, each of them consists of a picture and a title below. I try this way:

XAML (Style with a template inside of a ResourceDictionary):

<Style x:Key="myStyle" TargetType="{x:Type Button}">
<Setter Property="Width" Value="300"></Setter>
<Setter Property="Height" Value="320"></Setter>
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate  TargetType="{x:Type Button}">
            <Grid Margin="5 2" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"  Background="White" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Image Width="300" Height="250"  x:Name="picGraph" Source="picture1.png" />
                <TextBlock Grid.Row="1" Text="title1" HorizontalAlignment="Center" />
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

XAML (Usage):

<Button Style="{StaticResource TestGenResultsGraph}"/>

That's all good, but I want to be able to change the Source-property of the image and Text-property of the textblock when I use the Button (to use more than only picture1.png).

I tried to add a setter for a Source-property, but it doesn't work this way, because Button-control doesn't have it:

<Setter Property="Source" Value="picture1.png"/> <!-- Error: The member "Source" is not recognized or is not accessible-->

So generally I would like to have a possibility of usage like that:

<Button Style="{StaticResource myStyle}" Source="picture1.png" Title="title 1"/>

How can I make those properties of children being settable in the parent?

  • https://stackoverflow.com/questions/40657840/set-a-property-of-a-nested-element-in-an-wpf-style – ASh Aug 16 '22 at 14:47
  • `Button` has no `Source` property. Use the `Content` property instead. And in your template do `TemplateBinding` with the image's `Source` and the Button's `Content` property (or relativesource mode TemplateBinding). Might require a converter since Source wants an object of type `ImageSource` – lidqy Aug 16 '22 at 15:05

1 Answers1

0

A Button has indeed no Title or Source properties. If you don't want to create your own custom control, you should be able to use the Content and Tag properties:

<Button Style="{StaticResource myStyle}" Tag="picture1.png" Content="title 1"/>

Template:

...
<Image Width="300" Height="250"  x:Name="picGraph"
    Source="{Binding Tag, RelativeSource={RelativeSource AncestorType=Button}}"  />
mm8
  • 163,881
  • 10
  • 57
  • 88