Is there a way to make this style generic, for example, only change the StringFormat property of the bindings in a DataTrigger?
Inherit Style , and the new XAML will be as follows:
<TextBox> <TextBox.Style> <local:FlyingStyle Binding="{Binding ElementName=This, Path=SomeValue}" StringFormat="F2" /> </TextBox.Style> </TextBox>
Here is the class ...
public class FlyingStyle : Style { public FlyingStyle() : base(typeof(TextBox)) { } string _stringFormat; public string StringFormat { get { return _stringFormat; } set { _stringFormat = value; CheckInitialize(); } } Binding _binding; public Binding Binding { get { return _binding; } set { _binding = value; CheckInitialize(); } } void CheckInitialize() { if (StringFormat == null || Binding == null) { return; }// need both Setters.Add(CreateSetter(Binding, StringFormat)); var trigger = new Trigger { Property = UIElement.IsKeyboardFocusWithinProperty, Value = true, }; trigger.Setters.Add(CreateSetter(Binding)); Triggers.Add(trigger); } /// <summary>Creates the common <see cref="Setter"/>.</summary> static Setter CreateSetter(Binding binding, string stringFormat = null) { // must create a copy, because same binding ref but diff StringFormats var bindingCopy = new Binding { // these could be copies as well UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, ValidatesOnDataErrors = true, Mode = BindingMode.TwoWay, Path = binding.Path, AsyncState = binding.AsyncState, BindingGroupName = binding.BindingGroupName, BindsDirectlyToSource = binding.BindsDirectlyToSource, Converter = binding.Converter, ConverterCulture = binding.ConverterCulture, ConverterParameter = binding.ConverterParameter, ElementName = binding.ElementName, FallbackValue = binding.FallbackValue, IsAsync = binding.IsAsync, NotifyOnSourceUpdated = binding.NotifyOnSourceUpdated, NotifyOnTargetUpdated = binding.NotifyOnTargetUpdated, NotifyOnValidationError = binding.NotifyOnValidationError, //StringFormat = set below... TargetNullValue = binding.TargetNullValue, UpdateSourceExceptionFilter = binding.UpdateSourceExceptionFilter, ValidatesOnExceptions = binding.ValidatesOnExceptions, XPath = binding.XPath, //ValidationRules = binding.ValidationRules }; // mutex ElementName, so modify if needed // Source = binding.Source, // RelativeSource = binding.RelativeSource, if (stringFormat != null) { bindingCopy.StringFormat = stringFormat; } return new Setter(TextBox.TextProperty, bindingCopy); } }
Please note that my test was
- shared mainwindow
- impl INotifyPropertyChanged
SomeValue Property- DataContext = this
- x: Name = This
Jake berger
source share