Reputation: 4693
I would like to have a TextBox
that displays a number in currency format (by setting StringFormat=c
on the binding). When the TextBox
is selected (when IsKeyboardFocused==true
), I would like the formatting to go away, until the focus on the TextBox
is lost.
I found a way to do this, code pasted below. My problem with this is that the binding is specified inside the Style
- this means I have to retype the style for every TextBox
I want to do this for. Idealy I would like to put the style somewhere central, and reuse it for every TextBox
, with a different binding target for each.
Is there a way for me, using a Style
, to set a parameter on the existing binding, something like Text.Binding.StringFormat=""
? (As opposed to setting the entire value of Text to a newly defined Binding)
Other suggestions to accomplish this would also be appreciated.
Code (this works, it's just inconvenient):
<TextBox x:Name="ContractAmountTextBox">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="False">
<Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus, StringFormat=c}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsKeyboardFocused, ElementName=ContractAmountTextBox}" Value="True">
<Setter Property="Text" Value="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
Upvotes: 3
Views: 3244
Reputation: 292405
It is feasible with an attached property, but it means you have to replace the binding entirely, then put it back.
Here's a quick and dirty implementation:
public static class TextBoxBehavior
{
#region StringFormat
public static string GetStringFormat(TextBox obj)
{
return (string)obj.GetValue(StringFormatProperty);
}
public static void SetStringFormat(TextBox obj, string value)
{
obj.SetValue(StringFormatProperty, value);
}
public static readonly DependencyProperty StringFormatProperty =
DependencyProperty.RegisterAttached(
"StringFormat",
typeof(string),
typeof(TextBoxBehavior),
new UIPropertyMetadata(
null,
StringFormatChanged));
// Used to store the original format
private static readonly DependencyPropertyKey OriginalBindingPropertyKey =
DependencyProperty.RegisterAttachedReadOnly(
"OriginalBinding",
typeof(BindingBase),
typeof(TextBoxBehavior),
new UIPropertyMetadata(null));
private static void StringFormatChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = o as TextBox;
if (textBox == null)
return;
string oldValue = (string)e.OldValue;
string newValue = (string)e.NewValue;
if (!string.IsNullOrEmpty(oldValue) && string.IsNullOrEmpty(newValue))
{
// Update target for current binding
UpdateTextBindingSource(textBox);
// Restore original binding
var originalBinding = (BindingBase)textBox.GetValue(OriginalBindingPropertyKey.DependencyProperty);
if (originalBinding != null)
BindingOperations.SetBinding(textBox, TextBox.TextProperty, originalBinding);
textBox.SetValue(OriginalBindingPropertyKey, null);
}
else if (!string.IsNullOrEmpty(newValue) && string.IsNullOrEmpty(oldValue))
{
// Get current binding
var originalBinding = BindingOperations.GetBinding(textBox, TextBox.TextProperty);
if (originalBinding != null)
{
// Update target for current binding
UpdateTextBindingSource(textBox);
// Create new binding
var newBinding = CloneBinding(originalBinding);
newBinding.StringFormat = newValue;
// Assign new binding
BindingOperations.SetBinding(textBox, TextBox.TextProperty, newBinding);
// Store original binding
textBox.SetValue(OriginalBindingPropertyKey, originalBinding);
}
}
}
private static void UpdateTextBindingSource(TextBox textBox)
{
var expr = textBox.GetBindingExpression(TextBox.TextProperty);
if (expr != null &&
expr.ParentBinding != null &&
(expr.ParentBinding.Mode == BindingMode.Default // Text binds two-way by default
|| expr.ParentBinding.Mode == BindingMode.TwoWay
|| expr.ParentBinding.Mode == BindingMode.OneWayToSource))
{
expr.UpdateSource();
}
}
private static Binding CloneBinding(Binding original)
{
var copy = new Binding
{
Path = original.Path,
XPath = original.XPath,
Mode = original.Mode,
Converter = original.Converter,
ConverterCulture = original.ConverterCulture,
ConverterParameter = original.ConverterParameter,
FallbackValue = original.FallbackValue,
TargetNullValue = original.TargetNullValue,
NotifyOnSourceUpdated = original.NotifyOnSourceUpdated,
NotifyOnTargetUpdated = original.NotifyOnTargetUpdated,
NotifyOnValidationError = original.NotifyOnValidationError,
UpdateSourceExceptionFilter = original.UpdateSourceExceptionFilter,
UpdateSourceTrigger = original.UpdateSourceTrigger,
ValidatesOnDataErrors = original.ValidatesOnDataErrors,
ValidatesOnExceptions = original.ValidatesOnExceptions,
BindingGroupName = original.BindingGroupName,
BindsDirectlyToSource = original.BindsDirectlyToSource,
AsyncState = original.AsyncState,
IsAsync = original.IsAsync,
StringFormat = original.StringFormat
};
if (original.Source != null)
copy.Source = original.Source;
if (original.RelativeSource != null)
copy.RelativeSource = original.RelativeSource;
if (original.ElementName != null)
copy.ElementName = original.ElementName;
foreach (var rule in original.ValidationRules)
{
copy.ValidationRules.Add(rule);
}
return copy;
}
#endregion
}
Usage:
<TextBox x:Name="ContractAmountTextBox"
Text="{Binding Path=ContractAmount, UpdateSourceTrigger=LostFocus, StringFormat=c}">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="local:TextBoxBehavior.StringFormat" Value="N"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
Using this, you can also reuse the style for different TextBoxes
Upvotes: 7