Jerome Dreyer
Jerome Dreyer

Reputation: 144

UWP WinRTXamlToolkit: chart-labels with units

For an UWP-app I'm displaying a chart with height data and it currently looks like this: enter image description here

I'd like to have units for the y-values like 100 m, but I can only manage to get the value itself. I am able to put a static unit behind that value by "StringFormat" in the "AxisLabelStyle" like this

<Setter Property="StringFormat" Value="{}{0:0 m}" />

but unfortunately I need a dynamic unit (e.g. meters or feet).

Am I missing anything? Ideas?

Upvotes: 0

Views: 678

Answers (1)

Grace Feng
Grace Feng

Reputation: 16652

As we've discussed, this style is set by user. So I just use a ComboBox to select the style for test.

Here is my code:

<Charting:Chart x:Name="AreaChart" Title="Area Chart" Margin="0,0">
    <Charting:AreaSeries x:Name="areaseries" IndependentValuePath="Value" DependentValuePath="Number" IsSelectionEnabled="True" />
</Charting:Chart>

<ComboBox x:Name="comboBox" VerticalAlignment="Bottom" SelectionChanged="comboBox_SelectionChanged">
    <ComboBoxItem>Meters</ComboBoxItem>
    <ComboBoxItem>Feet</ComboBoxItem>
</ComboBox>

code behind is just for testing, I didn't tried to rebuild your chart in your picture:

public MainPage()
{
    this.InitializeComponent();
    this.Loaded += MainPage_Loaded;
}

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    LoadChartContents();
}

private void LoadChartContents()
{
    Random rand = new Random();
    List<ChartTest> testitem = new List<ChartTest>();

    for (int i = 0; i < 30; i++)
    {
        testitem.Add(new ChartTest() { Value = i, Number = rand.Next(0, 100) });
    }

    (AreaChart.Series[0] as AreaSeries).ItemsSource = testitem;
}

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    areaseries.IndependentAxis = new LinearAxis { Orientation = AxisOrientation.X };
    var axis = (LinearAxis)areaseries.IndependentAxis;
    var item = comboBox.SelectedItem as ComboBoxItem;
    if ((string)item.Content == "Meters")
    {
        var labelstyle = new Style(typeof(AxisLabel));
        labelstyle.Setters.Add(new Setter(AxisLabel.StringFormatProperty, "{0:0 m}"));
        axis.AxisLabelStyle = labelstyle;
    }
    else
    {
        var labelstyle = new Style(typeof(AxisLabel));
        labelstyle.Setters.Add(new Setter(AxisLabel.StringFormatProperty, "{0:0 feet}"));
        axis.AxisLabelStyle = labelstyle;
    }
}

And my is ChartTest class like this:

public class ChartTest
{
    public int Value { get; set; }
    public int Number { get; set; }
}

The key point here is dynamic adding AxisLabelStyle to AreaSeries in the SelectionChanged event of the ComboBox.

Upvotes: 1

Related Questions