Has anyone ever created a custom markup extension in WPF or Silverlight? When would you ever want or need to do this? Any tips or sources on how to do it?
An example would be for Localization:
A simple and effective way to localize application resources is to write a custom MarkupExtension that provides a localized value. The extension takes a parameter that is a unique resource key... [and then] looks up the value from a generic resource provider.
Note: You can not write custom markup extensions in silverlight.
Yes it is handy and I have created one myself. I created a markup extension called EvalBinding that takes a set of bindings as children and a C# evaluation string. It evaluates the C# to process the values from the child bindings so that I do not need to create many simple TypeConverter classes.
For example I can do this...
<EvalBinding Eval="(this[0] > this[1] ? 'GT' : 'LTE')">
<Binding ElementName="element1" Path="Size"/>
<Binding ElementName="element2" Path="Size"/>
<EvalBinding>
Where this is a reference to the array of child binding results.
For resources on implementing a MarkupExtension...
Hooray!!
This is implemented in Silverlight 5!!
And furthermore, now it's a generic interface instead of a class!!
Read this for an example.
I use a markup extension to standardise my validation bindings. So the benefit here is small, 4 of the defaults I don't have to set anymore, and if I wish to change them in the future, I do it here only.
using System;
using System.Windows.Data;
using System.Windows.Markup;
namespace ITIS
{
/// <summary>
/// Creates a normal Binding but defaults NotifyOnValidationError to True,
/// ValidatesOnExceptions to True, Mode to TwoWay and
/// UpdateSourceTrigger to LostFocus.
/// </summary>
public sealed class ValidatedBinding : MarkupExtension
{
public ValidatedBinding(string path)
{
Mode = BindingMode.TwoWay;
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
Path = path;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new Binding(Path) {
Converter = this.Converter,
ConverterParameter = this.ConverterParameter,
ElementName = this.ElementName,
FallbackValue = this.FallbackValue,
Mode = this.Mode,
NotifyOnValidationError = true,
StringFormat = this.StringFormat,
ValidatesOnExceptions = true,
UpdateSourceTrigger = this.UpdateSourceTrigger
};
}
public IValueConverter Converter { get; set; }
public object ConverterParameter { get; set; }
public string ElementName { get; set; }
public object FallbackValue { get; set; }
public BindingMode Mode { get; set; }
public string Path { get; set; }
public string StringFormat { get; set; }
public UpdateSourceTrigger UpdateSourceTrigger { get; set; }
}
}
© 2022 - 2024 — McMap. All rights reserved.