根据WPF中的值设置背景

时间:2018-06-02 20:45:04

标签: c# wpf binding toast dynamicresource

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

public class TestClass
{
    public delegate Task TestHandlerAsync(object sender);
    public event TestHandlerAsync TestAsync;

    private async Task<Exception[]> OnTestAsync()
    {
        var testAsync = this.TestAsync;

        if (testAsync == null)
        {
            return new Exception[0];
        }

        return await Task.WhenAll(
            from TestHandlerAsync d in testAsync.GetInvocationList()
            select ExecuteAsync(d));

        async Task<Exception> ExecuteAsync(TestHandlerAsync d)
        {
            try
            {
                await d(this);
                return null;
            }
            catch (Exception ex)
            {
                return ex;
            }
        }
    }

    public async Task TestTestAsync()
    {
        try
        {
            var exceptions = await OnTestAsync();

            foreach (var exception in exceptions)
            {
                if (exception != null)
                {
                    Program.ConsoleWriteLine($"{nameof(TestTestAsync)}: {exception.Message}", ConsoleColor.Green);
                }
            }
        }
        catch (Exception ex)
        {
            Program.ConsoleWriteLine($"{nameof(TestTestAsync)}: {ex.Message}", ConsoleColor.Green);
        }
    }
}

CustomMessage.xaml:

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

CustomMesage.xaml.cs:

<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>

ToastDto.cs:

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

和App.xaml:

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

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

1 个答案:

答案 0 :(得分:3)

您可以撰写自定义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>