Code Snippet
- <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
As any other converter after that we can simply add it to binding configuration:
Code Snippet
- Converter={StaticResource BoolToVisConverter}}
There are other ways of adding and instantiating converters in code though. For instance, what, if we don't want to go through the hassle of adding a converter in resources every time we want to use one? Below you have an ordinary converter with additional property - which changes the converter into a singleton.
Code Snippet
- public class ThingToThingConverter : IValueConverter
- {
- private static ThingToThingConverter _instance;
- public static ThingToThingConverter Instance
- {
- get
- {
- return _instance ?? (_instance = new ThingToThingConverter());
- }
- }
Thanks to this, we can now use above converter without adding it first to window's/control's resources. Like this:
Code Snippet
- Converter={x:Static Converters:ThingToThingConverter.Instance}}">
Another way of doing this is by using MarkupExtension, it's similar to the above, but I find is slightly more comfortable:
Code Snippet
- public class SmthToSmthConverter : MarkupExtension, IValueConverter
- {
- public static SmthToSmthConverter _converter = null;
- public SmthToSmthConverter()
- {
- }
- public override object ProvideValue(IServiceProvider serviceProvider)
- {
- if (_converter == null)
- _converter = new SmthToSmthConverter();
- return _converter;
- }
ProvideValue method is called whenever XAML processor examines a MarkupExtension node and returns our converter into the object graph. All this allows us to use the following markup:
Code Snippet
- Converter={Converters:ThingToThingEnumConverter}
No comments:
Post a Comment