Silverlight:如何在代码中更改AxisLabelStyle?

时间:2011-03-16 18:05:55

标签: silverlight coding-style charts

在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中。

任何人都可以提供帮助吗?谢谢!

1 个答案:

答案 0 :(得分: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类型,没有标签样式。