我想在WPF中创建一个“Hello World”。这是我的XAML:
<Grid>
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="Hello, WPF" VerticalAlignment="Center" FontSize="60" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
</Grid>
...和我的代码隐藏:
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
this.FontSize = 90;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
this.FontSize = 72;
}
当我将鼠标移到TextBlock时,字体应该设置为更大的尺寸,而在MouseLeave上它应该设置为更小的尺寸。
但是,字体大小不变。处理程序被成功调用,为什么字体大小不会改变?
答案 0 :(得分:7)
为您的TextBlock
命名并影响新的FontSize
<Grid>
<TextBlock Name="Tb" HorizontalAlignment="Center" TextWrapping="Wrap" Text="Hello, WPF" VerticalAlignment="Center" FontSize="60" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
</Grid>
和背后的代码
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
Tb.FontSize = 90;
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
Tb.FontSize = 72;
}
更好的解决方案
更好的解决方案是使用Trigger,不需要事件处理程序
<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>
答案 1 :(得分:4)
你必须从这样的对象中获取textBlock。在这种情况下,您不需要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;
}