Question

I am setting foreground of a label control as below using EnvironmentColors class in XAML. Note that I am using BrushKey here.

<Label Content="System Tray Notifications" Grid.Row="0" VerticalAlignment="Center" Padding="0" Foreground="{DynamicResource {x:Static vsui:EnvironmentColors.ToolWindowTextBrushKey}}"/>

However, I would like set this color using IValueConverter to decide the color to be set. But I do not know how I should return the same from Converter. Can you please let me know it can be done?

Was it helpful?

Solution

I found a way to do this. The difference in the link which was suggested in comment by Krekkon and Visual Studio extensions is that,

  • I am using EnvironmentColors and VsBrushes enum of Visual Studio SDK (so I could not do new SolidColorBrush(...))
  • I had to set it as a dynamic resource so that colors are set based on the theme selected in Visual Studio

So, my code in the converter is as follows.

public class MessageBackgroundConverter : BaseConverter, IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values != null)
        {
            var postedByUserId = Guid.Parse(values[0].ToString());
            var loggedInUserId = Guid.Parse(values[1].ToString());
            var control = values[2] as Border;
            if (control != null)
            {
                if (postedByUserId == loggedInUserId)
                {
                    control.SetResourceReference(Border.BackgroundProperty, VsBrushes.CommandBarGradientKey);
                    return null;
                }
                control.SetResourceReference(Border.BackgroundProperty, VsBrushes.ToolWindowBackgroundKey);
                return null;
            }
        }
        return Brushes.Transparent;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Note that I am using MultiValueConverter and passing the control for which color needs to be set too. This is because for setting the DynamicResource we need to use

control.SetResourceReference(...);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top