Reputation: 180
I want to create a "Hello World" in WPF. Here is my XAML:
<Grid>
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="Hello, WPF" VerticalAlignment="Center" FontSize="60" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
</Grid>
...and my code-behind:
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
this.FontSize = 90;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
this.FontSize = 72;
}
When I MouseOver the TextBlock, the font should be set to the larger size, and on MouseLeave it should be set to the smaller size.
However, the font size is unchanged. The handler is called successfully, so why did the font size not change?
Upvotes: 2
Views: 2477
Reputation: 2614
You must get textBlock from object like this. In this case you don't need name for TextBlock.
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
var block = sender as TextBlock;
block.FontSize = 90;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
var block = sender as TextBlock;
block.FontSize = 72;
}
Upvotes: 4
Reputation: 9944
Name your TextBlock
and affect the new FontSize
to it
<Grid>
<TextBlock Name="Tb" HorizontalAlignment="Center" TextWrapping="Wrap" Text="Hello, WPF" VerticalAlignment="Center" FontSize="60" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
</Grid>
and the code behind
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
Tb.FontSize = 90;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
Tb.FontSize = 72;
}
Better solution
and a better solution to do that is by using a Trigger, no event handler is required
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="Hello, WPF" VerticalAlignment="Center" >
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FontSize" Value="90"></Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="FontSize" Value="72"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
Upvotes: 8