Accessing colors in a resource dictionary from a value converter

后端 未结 1 556
野趣味
野趣味 2020-12-29 07:09

I defined several colors in a ResourceDictionary. e.g.:


  #FFF7F1F3
  

        
相关标签:
1条回答
  • 2020-12-29 07:29

    The annoying thing about using a converter parameter is that you have to add that text every single time you want to use the binding.

    Instead you could make the ResourceDictionary a property on your converter and set it when you instantiate the converter.

    code for converter:

    public class SomeConverter : IValueConverter
    {
        private ResourceDictionary _resourceDictionary;
        public ResourceDictionary ResourceDictionary
        {
            get { return _resourceDictionary; }
            set 
            {
                _resourceDictionary = value; 
            }
        }
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //do your own thing using the _dict
            //var person = value as Person
            //if (person.Status == "Awesome")
            //    return _resourceDictionary["AwesomeBrush"]
            //else
            //    return _resourceDictionary["NotAwesomeBrush"];
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
    }
    

    instantiate and use converter:

    <Window.Resources>
        <local:SomeConverter x:Key="MyConverter" >
            <local:SomeConverter.ResourceDictionary>
                <ResourceDictionary Source="SomeRandomResourceDictionary.xaml" />
            </local:SomeConverter.ResourceDictionary>
        </local:SomeConverter>
    </Window.Resources>
    
    ...
    
    <StackPanel Background="{Binding CurrentPerson, Converter={StaticResource MyConverter}}" >
    </StackPanel>
    
    0 讨论(0)
提交回复
热议问题