WPF入门:
模板思想,自定义一个模板类来实现重定义按钮。
xml
<Grid>
<Button Width="300" Height="100" Content="自定义按钮" Background="Pink" FontSize="50" Foreground="White">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="10">
<TextBlock x:Name="txtConent" Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="black"/>
<Setter TargetName="txtConent" Property="FontSize" Value="20"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
1.解析:
按钮的大小、内容、前背景、字体大小的实现:
xml
<Button Width="300" Height="100" Content="自定义按钮" Background="Pink" FontSize="50" Foreground="White">
定义一个按钮模板,在其中填写内容:
xml
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
....
</ControlTemplate>
</Button.Template>
按钮的外观,border是边框的意思,TemplateBinding是绑定的意思,不会直接将值给写死,在实现的时候传参调用。在border内部加入一个文本框。
xml
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="10">
<TextBlock x:Name="txtConent" Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
设置两个触发器,在指针移入的时候会变色+字体变化,点击的时候会变色。
xml
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="black"/>
<Setter TargetName="txtConent" Property="FontSize" Value="20"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Background" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
效果: