Есть ли способ сделать этот стиль общим, например, только изменение
свойство StringFormat привязки в DataTrigger?
Наследует Style
и новый XAML станет таким:
<TextBox>
<TextBox.Style>
<local:FlyingStyle Binding="{Binding ElementName=This, Path=SomeValue}" StringFormat="F2" />
</TextBox.Style>
</TextBox>
Вот класс ...
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);
}
}
Обратите внимание, что мой тест был
- универсальное MainWindow
- подразумевается INotifyPropertyChanged
SomeValue
свойство INPC
- DataContext = this
- x: Имя = Это