views:

146

answers:

1

Hi, I'd like to change the ContentTemplate of a ContentPresenter in the CodeBehind file. But if I run the Silverlight 4 application a XamlParseException with the error code 2260 occures.

foreach (ContentPresenter item in Headers)
{
    item.ContentTemplate = Parent.UnselectedHeaderTemplate;
}

if ((index >= 0) && (index < Headers.Count))
{
    ContentPresenter item0 = (ContentPresenter)Headers[index];
    item0.ContentTemplate = Parent.SelectedHeaderTemplate;
}

If I do only the foreach code without the code in the "if", it works. And if I only do the code in the "if" without the foreach it works too. But togheter (the "if"-code and the foreach-code) it doesn't work.

I have no idea why it doesn't work. The two templates look like this:

<Setter Property="UnselectedHeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"
                           Margin="10,-10"
                           FontSize="72"
                           Foreground="#FF999999"
                           CacheMode="BitmapCache"/>

            </DataTemplate>
        </Setter.Value>
    </Setter>

    <!-- SelectedHeader template -->
    <Setter Property="SelectedHeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"
                           Margin="10,-10"
                           FontSize="72" 
                           Foreground="{TemplateBinding Foreground}"
                           CacheMode="BitmapCache"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>

If you have an idea what problem is please tell me.

A: 

I can't explain why your code doesn't work but its horrible way to achieve this goal.

This sort of task is best handled with the VisualStateManager. Create two states "Selected" and "Unselected", leave the Unselected state empty and have the "Selected" state assign the "#FF999999" color to Foreground.

Now all your code needs to do is:-

VisualStateManager.GotoState(item, "Selected", false);

or

VisualStateManager.GotoState(item, "Unselected", false);

on the appropriate items.

AnthonyWJones