Silverlight ~ MVVM ~ Dynamically adjust the Style property based on model value

I have a class called Questionthat represents a question and answers. I have an application that displays an object of an ObservableCollection of objects Question. Each is Questiondisplayed as a StackPanel containing a TextBlock for wording questions, and a TextBox for the user to enter an answer. Questions are handled using the ItemsControl, and I initially set the StackPanel style of the questions using a StaticResource key called " IncorrectQuestion " (defined in the UserControl.Resources section of the page). In the UserControl.Resources section, I also defined the calld key CorrectQuestionwhich I need to somehow apply to the StackPanel of the question when the user answers the question correctly. My problem is that I am not sure how to dynamically change the style of the StackPanel, especially within the limitations of the ViewModel class (i.e. I don’t want to embed the style selection code in the "Code" code). My class Questionhas a property IsCorrectthat is set exactly when responding to a patch. I would like to somehow reflect the meaning IsCorrectin the form of a choice of style. How to do it?

+3
source share
1 answer

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>

BoolToStyleConverter, . : -

public class BoolToStyleConverter : BoolToValueConverter<Style> { }
+3

Source: https://habr.com/ru/post/1749065/


All Articles