我对WPF和XAML还不太熟悉,现在正在学习。
我找到了一位先前开发者编写的快速代码:
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<Border Name="buttonBorder" Background="{TemplateBinding Background}">
<Border.Effect>
<DropShadowEffect Opacity="0.0" />
</Border.Effect>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.8" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="true">
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.8" Direction="135"
ShadowDepth="3" BlurRadius="1" />
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="buttonBorder" Property="Background">
<Setter.Value>
<ImageBrush ImageSource="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" />
</Setter.Value>
</Setter>
<Setter TargetName="buttonBorder" Property="Effect">
<Setter.Value>
<DropShadowEffect Opacity="0.0"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
基本上,它只是一个带有基本鼠标悬停效果和禁用状态图像绑定到标记的按钮模板(似乎是一个丑陋的解决方案)。
我想创建一个自定义按钮,其工作方式与原始按钮类似,但我想公开两个自定义属性:NormalImage 和 DisabledImage。这些属性应为字符串类型而非 Uri。我想要使用图像路径 "apply.png" 而非 "pack://application:,,,/Resources/Apply.png"。
我想,为了拥有这样的自定义属性,我需要一个带有依赖属性的 UserControl?
基本上,我想按以下方式使用按钮:
<MyImageButton NormalImage="apply.png" DisabledImage="apply_disabled.png"/>
也许NormalImage/DisabledImage以后会被绑定到其他内容上,但这种可能性很小。
我找不到任何实现自定义属性基本按钮的示例,只能在网上找到一些花哨的按钮和控件。也许我使用的关键词不正确...
有人可以指向正确的文章或提供一些简单的代码供我尝试吗?
对于初学者来说,WPF非常复杂,有时它并不能像预期的那样工作,例如我仍然不理解为什么我可以将Trigger标签添加到ControlTemplate中,但我不能直接将Trigger标签添加到UserControl中...