Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为内容c添加颜色#_C#_Wpf - Fatal编程技术网

C# 为内容c添加颜色#

C# 为内容c添加颜色#,c#,wpf,C#,Wpf,我从我的XAML.CS中得到了这段代码 InitializeComponent(); this.question = answers; this.list_question.ItemsSource = answers; int num_of_questions = this.question.Count; int ps = num_of_questions/2; label_score.Content = Con

我从我的XAML.CS中得到了这段代码

 InitializeComponent();
        this.question = answers;
        this.list_question.ItemsSource = answers;
        int num_of_questions = this.question.Count;
        int ps = num_of_questions/2;

        label_score.Content = Convert.ToString(ca) + " / " +    Convert.ToString(num_of_questions);

        if (ca >= ps)
        {
            label_result.Content = "Passed!!"; 
        }
        else
        {
            label_result.Content = "Failed!!";
        } 
如果结果“通过”,文本颜色将为蓝色,如果结果失败,如何设置颜色。文本颜色为红色将显示在我的XAML表单中? 我正在C#中使用WPF应用程序:)谢谢。>^ ^

使用属性:

if (ca >= ps)
{
    label_result.Content = "Passed!!"; 
    label1.Foreground = Brushes.Blue;
}
else
{
    label_result.Content = "Failed!!";
    label1.Foreground = Brushes.Red;
}

当您刚开始时,使用代码隐藏会更容易。但您肯定希望尽早了解数据绑定和MVVM模式。你可以在网上找到很多优秀的资源,比如和。(从谷歌排名靠前的搜索结果中随机挑选,但两者的评分都很高)

你可以像下面这样添加触发器

 <Window.Resources>
        <Style x:Key="LabelStyle" TargetType="{x:Type Label}">
            <Style.Triggers>
                <Trigger Property="Content"  Value="Passed">
                    <Setter Property="Foreground" Value="Blue" />
                </Trigger>
                <Trigger Property="Content"  Value="Failed">
                    <Setter Property="Foreground" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Label Style="{StaticResource ResourceKey=LabelStyle}" Content="Failed" />
    </Grid>


谢谢你的帮助。xD我今天在我的项目中使用了数据绑定,但我只是c#的新手。感谢您提供的资源。这将给我更多的知识。如果您是第一次实现,那么最好在XAML文件本身中设置样式,而不是在编码中设置样式,这将在将来为您节省很多工作。