Search code examples
silverlightxamlchartssilverlight-toolkitstyling

Silverlight Toolkit Chart: Assign Hyperlink to Axis


I have a simple Silverlight Toolkit Chart which is bound to a collection of the following type:

public class ChartItemClass
{
    public string Name { get; set; }
    public double Value { get; set; }
    public string Url { get; set; }
}

I can get a Chart to display the Name (X-axis) and Value (Y-axis) correctly, but I would like the labels on the X-axis to be HyperlinkButtons to the Url property. The X-axis label should be something like the following:

<HyperlinkButton Content="*Name Property Here*" NavigateUri="*Url Property Here*" TargetName="_blank"></HyperlinkButton>

I found an example which allowed me to set the AxisLabelStyle for the X-axis so the Labels are now HyperlinkButtons. The problem is I haven't been able to assign/bind the Url property as the NavigateUri. Any ideas?


Solution

  • At first I will post the complete code and after that the explanation.

       <UserControl.Resources>
        <Style x:Key="hyperlinkStyle" TargetType="charting:AxisLabel">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="charting:AxisLabel">
                        <HyperlinkButton Content="{Binding Name}" NavigateUri="{Binding Url}" TargetName="_blank"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
    
    <charting:Chart>
        <charting:Chart.Series>
            <charting:ColumnSeries ItemsSource="{Binding Items}" DependentValueBinding="{Binding Value}" IndependentValueBinding="{Binding}">
                <charting:ColumnSeries.IndependentAxis>
                    <charting:CategoryAxis Orientation="X" AxisLabelStyle="{StaticResource hyperlinkStyle}" />
                </charting:ColumnSeries.IndependentAxis>
            </charting:ColumnSeries>
        </charting:Chart.Series>
    </charting:Chart>
    

    The trick is in this line:

    IndependentValueBinding="{Binding}"
    

    Using this binding you pass a whole object to the independent axis, not just a property. And after that you can get properties of a bound object in the control template of label:

    Content="{Binding Name}" NavigateUri="{Binding Url}"
    

    The Binding keyword instead of the TemplateBinding looks strange, but it is permitted and it works. And there is one remark: the Url property must contain the http prefix. It doesn't work with www.