c# - 根据 WPF 中的值设置背景

标签 c# wpf binding toast dynamicresource

我需要根据您在构造函数中收到的值来设置背景值。 类型是:

public enum EToastType
{
    Error,
    Info,
    Success,
    Warning
}

自定义消息.xaml:

<core:NotificationDisplayPart x:Class="Presentacion.Notificaciones.CustomMessage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:core="clr-namespace:ToastNotifications.Core;assembly=ToastNotifications"
mc:Ignorable="d"  Background="{**I NEED SET VALUE**}"
d:DesignHeight="60" d:DesignWidth="250">
<Grid  Margin="5">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="{Binding Title}" FontWeight="Bold" Foreground="White" />
    <TextBlock Text="{Binding Message}" FontWeight="Light" Foreground="White" Grid.Row="1" TextWrapping="Wrap" />
</Grid>

自定义消息.xaml.cs:

public partial class CustomMessage : NotificationDisplayPart
{
    public CustomMessage(ToastDto toast)
    {
        DataContext = toast;
        InitializeComponent();
    }
}

ToastDto.cs:

public class ToastDto
{
    public EToastType Color { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
}

和 App.xaml:

<Application 
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:system="clr-namespace:System;assembly=mscorlib"
         xmlns:options="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options">

<Application.Resources>
    <ResourceDictionary>            
        <Color x:Key="InformationColor">#147ec9</Color>
        <SolidColorBrush x:Key="InformationColorBrush" Color="{StaticResource InformationColor}" options:Freeze="True" />

        <Color x:Key="SuccessColor">#11ad45</Color>
        <SolidColorBrush x:Key="SuccessColorBrush" Color="{StaticResource SuccessColor}" options:Freeze="True" />

        <Color x:Key="ErrorColor">#e60914</Color>
        <SolidColorBrush x:Key="ErrorColorBrush" Color="{StaticResource ErrorColor}" options:Freeze="True" />

        <Color x:Key="WarningColor">#f5a300</Color>
        <SolidColorBrush x:Key="WarningColorBrush" Color="{StaticResource WarningColor}" options:Freeze="True" />

    </ResourceDictionary>
</Application.Resources>

然后根据发送到 CustomMessage 构造函数的 EToastType 值,CustomMessage 中的背景属性必须采用 App.xaml 的值

最佳答案

您可以编写自定义 IValueConverter 将您的 EToastType 转换为 Brush

public class EToastTypeToBrushConverter : IValueConverter
{
    public Brush Error { get; set; }
    public Brush Info { get; set; }
    public Brush Success { get; set; }
    public Brush Warning { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is EToastType type)
        {
            switch (type)
            {
                case EToastType.Error:
                    return Error;
                case EToastType.Info:
                    return Info;
                case EToastType.Success:
                    return Success;
                case EToastType.Warning:
                    return Warning;
            }
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        => throw new NotSupportedException();
}

通过使用此转换器,只需使用资源字典中的每个画笔属性初始化一个新实例。

<local:EToastTypeToBrushConverter x:Key="EToastTypeToBrushConverter"
    Info="{StaticResource InformationColorBrush}"
    Success="{StaticResource SuccessColorBrush}"
    Error="{StaticResource ErrorColorBrush}"
    Warning="{StaticResource WarningColorBrush}"/>

编辑:如果你想要一个更通用的IValueConverter,你可以编写这样的代码而不是EToastTypeToBrushConverter:

[ContentProperty(nameof(Conversions))]
public class EnumToObjectConverter : IValueConverter
{
    public Collection<EnumConversion> Conversions { get; } = new Collection<EnumConversion>();
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        => Conversions.FirstOrDefault(x => Equals(x.Source, value))?.Target;
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        => throw new NotSupportedException();
}

但是这样一来,XAML的使用会比较复杂:

<local:EnumToObjectConverter x:Key="EToastTypeToBrushConverter">
    <local:EnumConversion Target="{StaticResource InformationColorBrush}">
        <local:EnumConversion.Source>
            <local:EToastType>Info</local:EToastType>
        </local:EnumConversion.Source>
    </local:EnumConversion>
    <local:EnumConversion Target="{StaticResource SuccessColorBrush}">
        <local:EnumConversion.Source>
            <local:EToastType>Success</local:EToastType>
        </local:EnumConversion.Source>
    </local:EnumConversion>
    <local:EnumConversion Target="{StaticResource ErrorColorBrush}">
        <local:EnumConversion.Source>
            <local:EToastType>Error</local:EToastType>
        </local:EnumConversion.Source>
    </local:EnumConversion>
    <local:EnumConversion Target="{StaticResource WarningColorBrush}">
        <local:EnumConversion.Source>
            <local:EToastType>Warning</local:EToastType>
        </local:EnumConversion.Source>
    </local:EnumConversion>
</local:EnumToObjectConverter>

关于c# - 根据 WPF 中的值设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661008/

相关文章:

绑定(bind)到 Asp.NET MVC Core 中的 TimeSpan 属性

c# - 我应该如何在 .net core 3.0 中绑定(bind)来自 WPF 的 xaml 事件?

wpf - StackPanel 上的填充?

wpf - TabControl - 使 TabItem 出现在内容顶部

C# 创建动态按钮和 onClick 动态事件处理程序

c# - 给一句话设置颜色?

c# - 绑定(bind)不适用于 xamarin 形式的 MVVM。未找到 'ItemSelected' 的属性、可绑定(bind)属性或事件,

c# - 修改 Silverlight DataGrid 中的父数据行

c# - EditorConfig - 简化 bool 评估?

c# - 使用接口(interface)在 C# 中进行转换,以便能够使用所有对象功能