2016-08-14 86 views
0

我有一个用XAML编写的相当简单的自定义控件,但是我在编写一些依赖项属性时遇到了一些麻烦,所以颜色可以更改。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}" 

但我只是得到了以下错误:

“找不到静态成员的类型 '切换按钮' BackgroundColorProperty'”

“成员‘BACKGROUNDCOLOR’无法识别或无法访问。”

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

请有人帮忙/解释我要出错的地方。

+0

请提供更多的代码。我可以想象什么不起作用,但它会作为猜测结果 – lokusking

+1

作为说明,属性类型应该是刷子,而不是颜色。 – Clemens

回答

0

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

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

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

这应该为您找到依赖项属性。

+0

或者,写'Fill =“{Binding BackgroundColor,RelativeSource = {RelativeSource AncestorType = UserControl}}' – Clemens

0

谢谢大家的答案。我已经把它用于你的建议的组合。

所以有一个新的填充:

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

现在依赖属性的类型是刷的。

谢谢大家! :)