Change child control (contentcontrol) property on mouseover of parent

2.9k views Asked by At

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.

2

There are 2 answers

2
Rachel On BEST ANSWER

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>
0
Shakti Prakash Singh On

In order to achieve what I wanted, I used Rachel's advice as well as Samuel Slade's. I did it something like this:

<Button  x:Name="btnEditItem"  Style="{DynamicResource btnStyle}" Margin="5,0,0,0"   ToolTip="Edit Item" Click="btnEditItem_Click"> 
<ContentControl x:Uid="ContentControl_5" Content="ContentControl" Template=" {DynamicResource contentTemplate}" Margin="2.5"/>
</Button>

And I set the height and width of the button through btnStyle via Setter property and change the height and width of the button through the triggers.

This got me working perfectly. I appreciate all your help suggestions. I am not sure if I could have reached to this conclusion as I was thinking on a different route of child controls property. Thanks again.