Thursday, November 13, 2014

Converters String To Resource Converter

Note: This is not my original work. Have blogged it here just for my future reference and of course if someone wants to use it.

 Sometime during development you may want to add to your project string to Resource converter to display the message in Cultural specific language. This is a way to create such a converter through code. it is specially helpful when you want to create controls on the fly through code.

Converter class 
 public class StringToResourceConverter : IValueConverter
    {
        public Dictionary<string,string> StringResourceCollection { get; set; }
        public StringToResourceConverter()
        {
            StringResourceCollection = new Dictionary<string, string>();
        }

        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && StringResourceCollection.Keys.Any(s => s == value.ToString()))
            {
                return Resources.ResourceManager.GetString(StringResourceCollection[value.ToString()]);
            }

            return string.Empty;
        }

        public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }


Usage
            ///Declaration
            public StringToResourceConverter StringToResourceConverter { get; set; }
            
            //Initialization
            StringToResourceConverter = new StringToResourceConverter();
            StringToResourceConverter.StringResourceCollection.Add("0", "Set");
            StringToResourceConverter.StringResourceCollection.Add("1", "Remove");


            //attaching to converter property of comtrol
            var setLink = new FrameworkElementFactory(typeof(Button));
            setLink.SetBinding(Button.ContentProperty, new Binding(myString1+ myString2) { Converter = StringToResourceConverter });

No comments:

Post a Comment