c# - 如何以编程方式添加更多样式 setter ?当我尝试时,出现 InvalidOperationException 异常(SetterBaseCollection 正在使用中)

标签 c# wpf charts wpf-style

我的 App.xaml 文件中有多个样式定义。像这样:

<Application x:Class="MyClient.App" ... >
    <Application.Resources>
        <SolidColorBrush x:Key="color1" Color="#FF7D7D" />
        <SolidColorBrush x:Key="color2" Color="#FF7D7E" />

        <Style x:Key="styleFor1" TargetType="charting:ColumnDataPoint">
            <Setter Property="Background" Value="{StaticResource color1}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="charting:ColumnDataPoint">
                        <Grid>
                            <Rectangle>
                                <Rectangle.Fill>
                                    <LinearGradientBrush>
                                        <GradientStop Color="#ffff3737" Offset="0" />
                                        <GradientStop Color="#80000000" Offset="1" />
                                    </LinearGradientBrush>
                                </Rectangle.Fill>
                            </Rectangle>
                            <ToolTipService.ToolTip>
                                <StackPanel>
                                    <ContentControl Content="VALUES:" FontWeight="Bold" />
                                    <ContentControl Content="{TemplateBinding FormattedIndependentValue}" />
                                    <ContentControl Content="{TemplateBinding FormattedDependentValue}" />
                                </StackPanel>
                            </ToolTipService.ToolTip>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

我生成了一个图表。并为其指定 DataPointStyle:

Style dpStyle = Application.Current.Resources["styleFor1"]

之后,我想向此 dpStyle 添加更多 Setter。完成后,我将图表的 DataPointStyle 设置为此 dpStyle。然后我得到了异常(exception)。我应该怎么办?请指导我。

更新:

异常详细信息(可能需要):

InvalidOperationException 未处理

{“‘SetterBaseCollection’使用(密封)后,将无法修改。”}

TargetSite:{Void CheckSealed()}

最佳答案

我找到了解决办法。我必须使用 Style 类的构造函数的重载:

public Style(Type targetType, Style basedOn);

只需将 Application.Current... 中的样式传递给它即可解决问题。酷。

关于c# - 如何以编程方式添加更多样式 setter ?当我尝试时,出现 InvalidOperationException 异常(SetterBaseCollection 正在使用中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24165363/

相关文章:

wpf - 将线条、文本等数据绑定(bind)到 ItemsControl,以便在 Canvas 上进行类似 CAD 的矢量绘图

c#监听键盘组合

c# - .NET-无法构建项目

wpf - 是否有官方的 Windows Presentation Foundation (WPF) Logo ?

.net - .Net图表控件自动滚动/禁用自动缩放

javascript - 带有混合图表的 Chart.js OnClick 事件,我点击了哪个图表?

C# 无法加入主线程

c# - Entity Framework 延迟加载和更新模型

C# html超链接调用方法

javascript - 堆叠水平条未对齐图表 JS