首页 文章

如何反转WPF自定义控件的颜色

提问于
浏览
1

我正在为我的WPF应用程序创建一个自定义控件,我想知道如何在单击时反转控件的颜色 . 我已经得到它来响应鼠标点击,但当我尝试交换背景和前景画笔时,只有背景颜色发生变化 . 控件是模具控件,我希望颜色在选中时反转 . 我通过在控件模板中使用网格创建模具面,并将填充画笔设置为的椭圆 . 任何帮助将不胜感激 .

2 回答

  • 0

    在控件处于选定状态时,在模板中放置一个触发器,用 "{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" 替换 {TemplateBinding Foreground} ,反之亦然 . 您可以't use TemplateBinding from a setter, so you' ll需要使用TemplatedParent的RelativeSource进行常规绑定 . 下面是一个带有TextBlock的CheckBox示例,该TextBlock在选中时会反转颜色:

    <CheckBox Foreground="Blue" Background="LightGreen">
        <ContentControl.Template>
            <ControlTemplate TargetType="CheckBox">
                <TextBlock Name="TextBlock"
                            Background="{TemplateBinding Background}"
                            Foreground="{TemplateBinding Foreground}"
                            Text="Text">
                </TextBlock>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="TextBlock" Property="Background"
    Value="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}"/>
                        <Setter TargetName="TextBlock" Property="Foreground"
    Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </ContentControl.Template>
    </CheckBox>
    
  • 1

    你可以使用像素着色器,看看例如http://wpffx.codeplex.com/

    它有一个你可以应用的反转颜色

相关问题