Установить фон в зависимости от значения в WPF
Мне нужно установить значение фона в зависимости от значения, которое вы получите в конструкторе. Типы:
public enum EToastType
{
Error,
Info,
Success,
Warning
}
CustomMessage.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>
CustomMesage.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; }
}
И приложение. 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>
Затем в зависимости от значения EToastType, которое отправляется в конструктор CustomMessage, фоновое свойство в CustomMessage должно принимать значение App.xaml.
1 ответ
Вы можете написать кастом 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>