【问题标题】:WPF UserControl Modify Portion of GradientWPF UserControl 修改渐变部分
【发布时间】:2012-12-19 03:45:46
【问题描述】:

如果我有一个简单的用户控件Button 带有这样的背景...

<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
  <GradientStop Color="Red" Offset="1" />
  <GradientStop Color="Black" Offset="0" />
</LinearGradientBrush>

有没有办法暴露一个渐变停止点,这样使用控件的人可以只修改第一个(例如Red)并将渐变保持为Black

【问题讨论】:

  • 修改偏移量?颜色?
  • 那么从客户端使用控件(例如&lt;MyCustom:Button&gt;)如何修改该属性?
  • 这是用户可以使用颜色选择器/滑块等实时更改的内容,还是用户从下拉列表中选择颜色并将红色替换为新的颜色。两者在理论上都是可能的,尽管后一种选择更容易实现并且对您的软件负担更少。
  • 您是要在 UserControl 还是 MainWindow 中执行此操作
  • 在 MainWindow xaml 中,使用下面描述的 newb,这就是我现在正在尝试的。

标签: c# wpf button user-controls gradient


【解决方案1】:

我假设您的意思是让用户将渐变停止颜色设置为他们自己的 XAML 的一部分?如果是这样,您可以使用DependencyProperty 并将GradientStop.Color 绑定到它。

在 UserControl.cs 中:

    public CoolControl()
    {
        InitalizeComponent();
        SetValue(ColorProperty, Colors.Red); // or any default color
    }

    public static DependencyProperty ColorProperty = DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(CoolControl)); // replace CoolControl with the name of your UserControl

    public Color BackgroundColor
    {
        get
        {
            return (Color)GetValue(ColorProperty);
        }
        set
        {
            SetValue(ColorProperty, value);
        }
    }

在 UserControl.xaml 中:

    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="{Binding BackgroundColor, RelativeSource={RelativeSource AncestorType={x:Type my:CoolControl}}}" Offset="1" /> <!-- replace my:CoolControl with your namespace declaration and UserControl name -->
        <GradientStop Color="Black" Offset="0" />
    </LinearGradientBrush>

使用控件:

    <Grid>
        <my:CoolControl BackgroundColor="Blue" />
    </Grid>

【讨论】:

  • 这似乎是要走的路,用法是我想要的。它正在构建但不工作。我的按钮只是从白色变为黑色。另外,在UserControl.xaml 中,我有什么命名空间,就像你有my 一样,但我在控件中,它不会只是CoolControl
  • 不,即使在控件中,为了检查控件的类型(在我的示例中为“CoolControl”),您必须导入封装控件定义的命名空间。
  • 我现在明白了,是的,确实有效。谢谢你。唯一不起作用的是构造函数的默认颜色`:Colors.Red, the button just ends up black. Does the control automatically get the property value at start? If I add GradientColor = Colors.Red`,它可以工作。
  • 你是对的。事实证明,如果没有初始化或其他东西,颜色显然是白色(非空)。我测试时的默认颜色是白色,所以我没有注意到。道歉。答案已编辑。很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多