Silverlight 4 - 在运行时从资源字典中检索纯色画笔?
我正在尝试从 C# 检索资源字典 (Styles.xaml) 中预定义的纯色画笔。
问题是,当我运行以下代码时,什么也没有发生:
private void LinkContinue_MouseEnter(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = (SolidColorBrush)Resources["HoverColorBrush"];
}
但是,如果我在代码中显式设置背景,它运行得很好:
private void LinkContinue_MouseLeave(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = new SolidColorBrush(Colors.Gray);
}
有什么想法吗?
I am trying to retrieve a solid color brush pre-defined in a resource dictionary (Styles.xaml) from C#.
The problem is that when i run the following code nothing happens:
private void LinkContinue_MouseEnter(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = (SolidColorBrush)Resources["HoverColorBrush"];
}
However if I set the background in code explicitly it runs fine:
private void LinkContinue_MouseLeave(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = new SolidColorBrush(Colors.Gray);
}
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
语法
Resources["HoverColorBrush"]
查找存储在当前对象的资源中的资源。在本例中,是包含方法LinkContinue_MouseEnter
的类实例的资源。如果您想使用与
{StaticResource HoverColorBrush}
相同的查找机制,则需要使用FindResource
方法:FrameworkElement.FindResource 方法
但是,如幸运的是,Silverlight 不支持
FindResource
,因此您需要直接在Styles.xaml
中定义的ResourceDictionary
中查找资源,或推出您自己的FindResource
。以下是关于此主题的博客文章和示例代码:
The syntax
Resources["HoverColorBrush"]
looks up a resource stored in the resources of the current object. In this case, the resources of the instance of the class that contains the methodLinkContinue_MouseEnter
.If you want to use the same lookup mechanism that
{StaticResource HoverColorBrush}
would use, you need to use theFindResource
method instead:FrameworkElement.FindResource Method
But, as luck would have it, Silverlight does not support
FindResource
and so you need to either look up the resource directly in theResourceDictionary
defined inStyles.xaml
, or roll your ownFindResource
.Here is a blog article on this topic with sample code:
所以答案是
Application.Current.Resources["ResourceName"] as SolidColorBrush
!谁会知道 Resources 对象指向页面的资源字典?呃呃呃So the answer was
Application.Current.Resources["ResourceName"] as SolidColorBrush
! Who would've known that the Resources object points to the resource dictionary for the page? UGHHH