【问题标题】:XAML Custom Control - Color Property BindingXAML 自定义控件 - 颜色属性绑定
【发布时间】:2016-08-14 16:40:49
【问题描述】:

我有一个用 XAML 编写的相当简单的自定义控件,但我在编写一些依赖属性以便更改颜色时遇到了一些麻烦。

这是我们感兴趣的控件。

<Viewbox>
  <Path Name="shape" Fill="Gray" Data="abc"/>
</Viewbox>
<ControlTemplate.Triggers>
  <Trigger Property="IsChecked" Value="True">
    <Setter TargetName="shape" Property="Fill" Value="Gold" />
  </Trigger>
</ControlTemplate.Triggers>

我想要实现的是将此处的填充(灰色和金色)替换为我可以更改为使用控件的属性。

所以我可以结束这个

<MyControl BackColor="Blue" ForeColor="Red" />

我尝试了一些不同的视频,包括 MVA 视频,但我不确定我哪里出错了。

我已经尝试过这个依赖属性。

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

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BackgroundColorProperty =
        DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(StarRatingControl), new PropertyMetadata(Color.FromRgb(0,0,0)));

然后使用

Fill="{TemplateBinding BackgroundColor}"

但我只是收到以下错误:

“在类型‘ToggleButton’上找不到静态成员‘BackgroundColorProperty’。”

“成员“BackgroundColor”无法识别或无法访问。”

这两个都在 XAML 文件中,而不是 CS 文件中。

请有人帮助/解释我哪里出错了。

【问题讨论】:

  • 请提供更多代码。我可以想象什么不起作用,但结果是猜测
  • 请注意,属性类型应该是 Brush,而不是 Color。

标签: c# wpf xaml


【解决方案1】:

确保您的页面或用户控件具有名称,以便使用 pageRoot 进行演示。

然后使用以下代码绑定到属性。

Fill="{Binding BackgroundColor, ElementName=pageRoot"}

这应该会为你找到依赖属性。

【讨论】:

  • 或者,写Fill="{Binding BackgroundColor, RelativeSource={RelativeSource AncestorType=UserControl}}
【解决方案2】:

感谢大家的回答。结合您的建议,我已经成功了。

所以有一个新的填充:

Fill="{Binding StarBackgroundColor, RelativeSource={RelativeSource AncestorType=UserControl}}"

并且依赖属性现在是 Brush 类型。

谢谢大家! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2011-05-11
    • 2017-12-22
    • 2012-08-07
    相关资源
    最近更新 更多