【问题标题】:Silverlight: How to change AxisLabelStyle in code behind?Silverlight:如何在后面的代码中更改 AxisLabelStyle?
【发布时间】:2011-03-16 18:05:54
【问题描述】:

在 xaml 文件中,我们可以通过以下方式更改 AxisLabelStyle:

<chartingToolkit:ColumnSeries.IndependentAxis>
    <chartingToolkit:CategoryAxis Orientation="X">
       <chartingToolkit:CategoryAxis.AxisLabelStyle>
         <Style TargetType="chartingToolkit:AxisLabel">
            <Setter Property="Template">
               <Setter.Value>
                   <ControlTemplate TargetType="chartingToolkit:AxisLabel">
                         <!--some code here-->
                   </ControlTemplate>
               </Setter.Value>
            </Setter>
         </Style>
       </chartingToolkit:CategoryAxis.AxisLabelStyle>
    </chartingToolkit:CategoryAxis>
</chartingToolkit:ColumnSeries.IndependentAxis>

我的问题是:如何在后面的代码中添加 AxisLabelStyle?

我知道我们可以通过这样做来添加 DataPointStyle:

ColumnSeries CS = new ColumnSeries();
CS.DataPointStyle = Application.Current.Resources["ByteBlocksColumns"] as Style;

但显然我们不能像这样直接更改 AxisLabelStyle,因为 AxisLabelStyle 在 CategoryAxis 内。

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 但是您可以使用以下方式获取轴:_chart.ColumnSeries[0].IndependentAxis.AxisLabelStyle = ...;这段代码我没有测试过,所以不知道这段代码能不能解决你的问题。
  • 感谢您的评论。我以前试过这个,但在 IndependentAxis 我找不到 AxisLabelStyle。
  • 我已经发布了适用于我的应用程序的答案。

标签: silverlight coding-style charts


【解决方案1】:

我稍微改变了你的xaml

    <charting:Chart>
        <charting:ColumnSeries x:Name="CS" ItemsSource="{Binding Items}" IndependentValuePath="X" DependentValuePath="Y">
            <charting:ColumnSeries.IndependentAxis>
                <charting:CategoryAxis Orientation="X" />
            </charting:ColumnSeries.IndependentAxis>
        </charting:ColumnSeries> 
    </charting:Chart>

上面的xaml可以用c#写成这样:

var CS = new ColumnSeries
         {
             ItemsSource = model.Items,
             IndependentValuePath = "X",
             DependentValuePath = "Y",
             IndependentAxis = new CategoryAxis { Orientation = AxisOrientation.X }
         };   

现在在代码隐藏中,您可以通过这种方式设置 AxisLabelStyle 属性:

var labelStyle = new Style(typeof(AxisLabel));
labelStyle.Setters.Add(new Setter(AxisLabel.StringFormatProperty, "Category {0}"));

var axis = (CategoryAxis)CS.IndependentAxis;
axis.AxisLabelStyle = labelStyle;

不要忘记将IndependentAxis 属性转换为正确的类型,因为默认情况下它具有IAxis 类型,它没有标签样式。

【讨论】:

  • 嗨,Vorrtex。在我的应用程序中,我在运行时添加了 MyColumnSeries。因此,当我无法获取轴 = (CategoryAxis)MyColumnSeries.IndependentAxis。当我尝试设置轴的 AxisLabelStyle 时,它​​会抛出一个空引用异常。
  • @Mrainy 创建 ColumnSeries 时,在下一行设置 IndependentAxis 属性。 CS.IndependentAxis = new CategoryAxis{Orientation = AxisOrientation.X};
  • @Mrainy 我已经编辑了我的答案,检查第二和第三块代码。
  • 非常感谢!你的回答给了我很多启发。
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 2014-08-01
  • 2016-06-05
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多