我在 XAML 中为 SystemColors 定义了资源。如果我将 Foregroung 属性直接设置为 TextBlock,效果会很好。但是,如果我在样式中分配前景属性,我会收到如下所示的错误。我不确定问题是什么以及如何解决。非常感谢任何想法!
当我直接在texblock中设置前景时的代码。它运行良好
<TextBlock Text="WindowTextColor" Foreground="{Binding WindowTextColor, Source={StaticResource SystemColors}, Converter={StaticResource colorConverter}}" />
通过样式设置前景属性时的代码。我的应用程序崩溃了:
<UserControl.Resources>
<local:ColorToBrushConverter x:Key="colorConverter" />
<local:SystemColorsWrapper x:Key="SystemColors" />
<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
<Setter Property="Foreground" Value="{Binding WindowColor, Source={StaticResource SystemColors}, Converter={StaticResource colorConverter}}"/>
</Style>
</UserControl.Resources>
<Grid Background="#FFB8B8B8">
<TextBlock Text="WindowColor" Style="{StaticResource TextBlockStyle1}" />
</Grid>
我得到的错误:
出现 System.Windows.Markup.XamlParseException Message=Set property '' 引发异常。 [行:11 位置:41] 行号=11 线位置=41 堆栈跟踪: 在 System.Windows.Application.LoadComponent(对象组件,Uri resourceLocator) 在 SilverlightSysColors.MainPage.InitializeComponent() 在 SilverlightSysColors.MainPage..ctor() 内部异常:System.NotSupportedException Message=无法设置只读属性“”。 堆栈跟踪: 在 MS.Internal.XamlMemberInfo.SetValue(对象目标,对象值) 在 MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType、XamlQualifiedObject& inObj、XamlPropertyToken inProperty、XamlQualifiedObject& inValue) 内部异常:
最佳答案
您不能在 Setter
中包含绑定(bind)。绑定(bind)应用于 Setter
的 ValueProperty
依赖属性,这并不是您真正的意图。发生的情况是在 Xaml 解析期间应用样式(在绑定(bind)可以应用其值之前),这反过来导致样式被密封。当绑定(bind)尝试调整 Setter
的值时,它会失败,因为一旦使用了样式,值就会变为只读。
编辑
根据我的猜测,动态绑定(bind)并不是真正必要的解决方法,您只需要一种方便的方法来访问 SystemColors
静态类的成员。我的方法是创建 ResourceDictionary
的派生类,以将一组完整的资源传送到 SystemColors
类,包括每个属性的 Color 和 Brush,并相应地命名。一点点反射(reflection)是有帮助的:-
public class SystemColorsResources : ResourceDictionary
{
public SystemColorsResources()
{
foreach (PropertyInfo pi in typeof(SystemColors).GetProperties())
{
Color c = (Color)pi.GetValue(null, null);
Add(pi.Name, c);
Add(pi.Name.Replace("Color", "Brush"), new SolidColorBrush(c));
}
}
}
在您的应用程序中使用此类,在 App.Xaml 的 MergedDictionaries
列表中包含它的一个实例:-
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<local:SystemColorsResources />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
现在您可以使用系统颜色属性名称及其“画笔”变体作为直接的静态资源:-
<UserControl.Resources>
<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource WindowBrush}" />
</Style>
</UserControl.Resources>
<Grid Background="#FFB8B8B8">
<TextBlock Text="WindowColor" Style="{StaticResource TextBlockStyle1}" />
</Grid>
关于silverlight - 无法在 Silverlight 的样式中添加系统颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5816238/