【问题标题】:How to invert the colors of a WPF custom control如何反转 WPF 自定义控件的颜色
【发布时间】:2010-07-25 11:07:02
【问题描述】:

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

【问题讨论】:

    标签: c# wpf custom-controls


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      在您的模板中放置一个触发器,当您的控件处于选定状态时,它将用"{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" 替换{TemplateBinding Foreground},反之亦然。您不能使用来自 setter 的 TemplateBinding,因此您需要使用具有 TemplatedParent 的 RelativeSource 的常规绑定。下面是一个带有 TextBlock 的 CheckBox 示例,它在选中时会反转颜色:

      <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>
      

      【讨论】:

      • 谢谢。在我发现我的 Selected 属性需要是一个 DependancyProperty 之后,它工作得很好。
      猜你喜欢
      • 1970-01-01
      • 2020-02-20
      • 2011-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多