【发布时间】:2016-05-27 04:03:40
【问题描述】:
我正在尝试获取一个按钮以在执行操作后更改颜色。我的按钮背景设置为SystemControlBackgroundAccentBrush,我基本上想在点击后获得“相反/互补”颜色。
我找到了这篇文章:
Using a complimentary accent color
这似乎是我想要的。我不得不稍微修改一下代码,因为它似乎特定于 windows phone 而不是 UWP。下面是我更改的类,但请注意,我没有包含上面文章中的整个代码,因为它保持不变:
public class AccentComplimentBrush : ViewModelBase
{
/// <summary>
/// The resource name - as it can be referenced by within the app
/// </summary>
private const string ResourceName = "AccentComplimentBrush";
/// <summary>
/// Initializes a new instance of the <see
cref="AccentComplimentBrush"/> class.
/// </summary>
public AccentComplimentBrush()
{
try
{
//// This doesn't work in the designer - so don't even try
if (this.IsInDesignMode)
{
return;
}
// Make sure we don't try and add the resource more than once - would
//happen if referenced on multiple pages or in app and page(s)
if (!Application.Current.Resources.ContainsKey(ResourceName))
{
var currentAccentColorHex = (SolidColorBrush)Application.Current.Resources["SystemControlBackgroundAccentBrush"];
var hsl = HslColor.FromColor(currentAccentColorHex.Color);
hsl.ConvertToCompliment();
Color compliment = hsl.ToColor();
Application.Current.Resources.Add(ResourceName, new SolidColorBrush(compliment));
}
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine("Something went wrong - ask for your money back");
System.Diagnostics.Debug.WriteLine(exc);
}
}
}
这是从 XAML 中调用它的方式:
-
首先类被初始化(并且它被初始化好了)
<UserControl.Resources> <common:AccentComplimentBrush x:Key="AccentComplimentBrush" /> </UserControl.Resources> 当它通过上述类的代码时,它找到相关资源,获取相关颜色,获取补色并将其转换回资源并添加到应用程序的资源中。如前所述,我已经检查了所有这些,一切正常。
请注意,它是一个圆形按钮,它包含一个椭圆,我正在尝试将笔触和填充属性分配给新画笔:
<Ellipse Stroke="{StaticResource AccentComplimentBrush}"
Fill="{StaticResource AccentComplimentBrush}"
StrokeThickness="2">
</Ellipse>
这是我得到的错误:
找不到与此错误代码关联的文本。 未能分配给属性“Windows.UI.Xaml.Shapes.Shape.Fill”。 [行:301 位置:46]
从错误看来,分配类生成的“画笔”时出现问题。
请注意,如果我硬编码 ThemeResource 或实际颜色,Ellipse 代码就可以正常工作。
有什么办法可以解决这个问题吗?有没有更简单的解决方案?
谢谢。
【问题讨论】:
标签: xaml win-universal-app xamlparseexception