Silverlight ~ MVVM ~ 根据模型值动态设置 Style 属性

标签 silverlight mvvm coding-style

我有一个名为 Question 的类,它表示一个问题及其答案。我有一个呈现 Question 对象的 ObservableCollection 的应用程序。每个 Question 都呈现为一个 StackPanel,其中包含一个用于问题措辞的 TextBlock 和一个供用户输入答案的 TextBox。这些问题是使用 ItemsControl 呈现的,我最初使用名为“IncorrectQuestion”(在页面的 UserControl.Resources 部分中定义)的 StaticResource 键设置问题的 StackPanel 的样式。在 UserControl.Resources 部分,我还定义了一个名为“CorrectQuestion”的键,当用户正确回答问题时,我需要以某种方式将其应用于问题的 StackPanel。我的问题是我不确定如何动态更改 StackPanel 的样式,特别是在 ViewModel 类的约束内(即我不想在 View 的代码隐藏中放置任何样式选择代码)。我的 Question 类有一个 IsCorrect 属性,在回答更正时准确地设置了该属性。我想以某种方式以样式选择的形式反射(reflect) IsCorrect 值。我该怎么做?

最佳答案

使用值转换器是一种解决方案。

<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 的基础是基于此blog post . 创建为:-

public class BoolToStyleConverter : BoolToValueConverter<Style> { }

关于Silverlight ~ MVVM ~ 根据模型值动态设置 Style 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999624/

相关文章:

coding-style - 为什么要使用短路码?

silverlight - 如何在 Blend 中编辑路径

apache-flex - 比较 FLEX、JavaFX 和 Silverlight

c# - 如何在 ObservableCollection 构建的 View 中动态设置用户控件的 grid.column/row

android 中的 mvvmcross touch 命令绑定(bind)

java - 来自 C,我需要一些帮助来弄清楚如何最好地从输入字符串生成国际象棋位图

silverlight - 使用 Windows 8/WinRT 在 Metro 应用中 PInvoke

javascript - 从 JavaScript 字符串保存文件而不访问服务器

javascript - 数据如何绑定(bind)到 Kendo-Knockout ListView 中的元素?

c# - WinForms - DataGridView 从 GroupBox 继承样式