wpfpropertiestriggerschildcontrol

Change child control (contentcontrol) property on mouseover of parent


I am new to WPF and am not able to figure out how to change the property of the child ContentControl of the Button control on mouse over. My code looks something like this:

<Button x:Name="btnAddItem" Height="25" Width="25" Margin="5,0,0,0"
        Style="{DynamicResource btnStyle}" ToolTip="Add Item">
    <ContentControl Content="ContentControl" Height="20" Width="20"
            Template="{DynamicResource contentTemplate}" />
</Button>

Now, when in the MouseOver event of the Button, I would like to change the size of the Button as well as the size of the child ContentControl. The ContentControl actually contains a vector image for the Button. Please help.


Solution

  • Your Button will automatically stretch to fit the size of it's contents, so get rid of it's Height and Width properties. If you want to maintain the space between the edge of the Button and the ContentControl, use the ContentControl's Margin property.

    Then, use a DataTrigger in your ContentControl's Style to change the Height/Width when the mouse is over it. Be sure you set Height/Width in your style instead of in your <ContentControl> tag, because if you set it in the tag it will take precedence over the triggered value so will never change.

    <Style x:Key="MyContentControlStyle" TargetType="{x:Type ContentControl}">
        <Setter Property="Height" Value="20" />
        <Setter Property="Width" Value="20" />
        <Setter Property="Margin" Value="5" />
        <Setter Property="Content" Value="ContentControl" />
        <Setter Property="Template" Value="{DynamicResource contentTemplate}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=btnAddItem, Path=IsMouseOver}" Value="True">
                <Setter Property="Height" Value="20" />
                <Setter Property="Width" Value="20" />
            </DataTrigger >
        </Style.Triggers>
    </Style>
    
    
    <Button x:Name="btnAddItem" Height="25" Width="25" Margin="5,0,0,0"
            Style="{DynamicResource btnStyle}" ToolTip="Add Item">
        <ContentControl Style="{StaticResource MyContentControlStyle}" /> 
    </Button>