views:

159

answers:

1

I have a class called Question that represents a question and it's answer. I have an application that renders an ObservableCollection of Question objects. Each Question is rendered as a StackPanel that contains a TextBlock for the question verbiage, and a TextBox for the user to enter in an answer. The questions are rendered using an ItemsControl, and I have initially set the Style of the Questions's StackPanel using a StaticResource key called 'IncorrectQuestion' (defined in UserControl.Resources section of the page). In the UserControl.Resources section, I've also defined a key calld 'CorrectQuestion' which I need to somehow apply to the Question's StackPanel when the user correctly answers the question. My problem is I'm not sure how to dynamically change the Style of the StackPanel, specifically within the constraints of a ViewModel class (i.e. I don't want to put any style selection code in the View's code-behind). My Question class has an IsCorrect property which is accurately being set when the correction is answered. I'd like to somehow reflect the IsCorrect value in the form of a Style selection. How do I do that?

+1  A: 

Using a value converter is a solution.

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.Resources>
        <local:BoolToStyleConverter x:Key="Correctness">
            <local:BoolToStyleConverter.FalseValue>
                <Style TargetType="TextBox">
                    <Setter Property="Background" Value="Salmon" />
                </Style>
            </local:BoolToStyleConverter.FalseValue>
            <local:BoolToStyleConverter.TrueValue>
                <Style TargetType="TextBox">
                    <Setter Property="Background" Value="AliceBlue" />
                </Style>
            </local:BoolToStyleConverter.TrueValue>
        </local:BoolToStyleConverter>
    </Grid.Resources>
    <ItemsControl ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Question}" />
                    <TextBox x:Name="Answer" Text="{Binding Answer, Mode=TwoWay}"
                       Style="{Binding IsCorrect, Converter={StaticResource Correctness}}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>        
</Grid>

You can find the basis for the BoolToStyleConverter is based on this blog post. Created as:-

public class BoolToStyleConverter : BoolToValueConverter<Style> { }
AnthonyWJones
I tried using a Value Converter but I coulnd't get it to work. I think I was just doing something wrong. I will revisit that option. Cheers!
eponymous23