我想在 wpf 中设计一个灵活的图像按钮。
首先,我在名称空间“ImageButton”中创建了一个 WPF 自定义控件库,如下所示:
namespace ImageButton
{
public class ImageButton : Button
{
static ImageButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));
}
#region DisplayMode
[System.ComponentModel.Category("ImageButton")]
public ImageDisplayMode DisplayMode
{
get { return (ImageDisplayMode)GetValue(DisplayModeProperty); }
set { SetValue(DisplayModeProperty, value); }
}
public static readonly DependencyProperty DisplayModeProperty =
DependencyProperty.Register("DisplayMode", typeof(ImageDisplayMode), typeof(ImageButton), new FrameworkPropertyMetadata(ImageDisplayMode.ImageAboveText), displaymodevalidate);
public static bool displaymodevalidate(object value)
{
return value is ImageDisplayMode;
}
#endregion
}
}
在命名空间“ImageButton”中,我定义了一个名为“ImageDisplayMode”的枚举,如下所示:
public enum ImageDisplayMode
{
ImageAboveText = 1,
TextAboveImage = 2,
ImageBeforeText = 3,
TextBeforeImage = 4
}
Generic.xaml 文件修改如下:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ImageButton">
<Style x:Name="style1" TargetType="{x:Type local:ImageButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ImageButton}">
<Button Background="Transparent">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Image Grid.ColumnSpan="2" Name="img1" Width="{TemplateBinding ImageWidth}" Stretch="{TemplateBinding ImageStretch}" Height="{TemplateBinding ImageHeight}" Source="{TemplateBinding Image}"/>
<TextBlock Grid.ColumnSpan="2" Grid.Row="1" Name="lbl1" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Text="{TemplateBinding Text}"/>
</Grid>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
上面代码的结果如下图:
[图片]
文字
我想要:当我更改 imagebutton 的“DisplayMode”属性的值时,对于每个可能的值,控件更改为以下形式:
1-------------------------------------------------
[图片]
文字
2-------------------------------------
文字
[图片]
3------------------------------------------------
[图片]文字
4----------------------------------------------------
文字[图片]
我想,我必须在 Generic.xaml 代码的网格中定义触发器,如下所示:
<Grid.Triggers>
<Trigger Property="DisplayMode" Value="2">
<Setter Property="Grid.Row" TargetName="lbl1" Value="0"/>
<Setter Property="Grid.Row" TargetName="img1" Value="1"/>
</Trigger>
</Grid.Triggers>
请告诉我:
我该怎么做?
非常感谢您