自定义WPF SButton控件点击背景不切换问题求助
问题排查与修复方案
嘿,我帮你找到了问题的根源!你的自定义SButton点击时背景没切换为设置的黑色,核心问题出在ControlTemplate触发器里的绑定指向错误。
为什么会失效?
看你当前的触发器代码:
<Trigger Property="IsPressed" Value="true"> <Setter Property="Background" TargetName="B" Value="{Binding PressBackground, RelativeSource={RelativeSource Self}}"/> </Trigger>
这里的RelativeSource={RelativeSource Self}指的是目标元素B(也就是那个Border控件),但Border并没有你自定义的PressBackground依赖属性,所以这个绑定根本找不到有效值,自然不会切换背景。
怎么修复?
你需要让绑定指向应用这个模板的SButton控件本身,也就是TemplatedParent。有两种写法都可以:
写法1:用TemplateBinding(推荐,更简洁)
TemplateBinding本质就是{Binding RelativeSource={RelativeSource TemplatedParent}}的简写,专门用于控件模板内部绑定到控件自身的属性:
<Trigger Property="IsPressed" Value="true"> <Setter Property="Background" TargetName="B" Value="{TemplateBinding PressBackground}"/> </Trigger>
写法2:显式指定RelativeSource为TemplatedParent
如果需要更明确的写法,可以用这个:
<Trigger Property="IsPressed" Value="true"> <Setter Property="Background" TargetName="B" Value="{Binding PressBackground, RelativeSource={RelativeSource TemplatedParent}}"/> </Trigger>
修复后的完整样式代码
修改后的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:SealBase"> <Style TargetType="{x:Type local:SButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:SButton}"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" VerticalAlignment="{TemplateBinding VerticalAlignment}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" Background="{TemplateBinding Background}" Name="B"> <TextBlock FontSize="{TemplateBinding FontSize}" Foreground="{TemplateBinding Foreground}" FontFamily="{TemplateBinding FontFamily}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"> <ContentPresenter></ContentPresenter> </TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="true"> <Setter Property="Background" TargetName="B" Value="{TemplateBinding PressBackground}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
额外优化建议
你的模板里用TextBlock包裹ContentPresenter其实有点多余,ContentPresenter本身可以直接继承控件的字体、对齐等属性,你可以简化模板,去掉外层的TextBlock,直接把ContentPresenter放在Border里,这样更符合WPF的最佳实践:
<Border ...> <ContentPresenter FontSize="{TemplateBinding FontSize}" Foreground="{TemplateBinding Foreground}" FontFamily="{TemplateBinding FontFamily}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/> </Border>
这样修改后,点击按钮时背景就会正确切换为你设置的黑色啦!
内容的提问来源于stack exchange,提问作者Melon NG
相关产品推荐
相关产品推荐

