我希望TextBox
显示货币格式的数字(通过在绑定上设置StringFormat=c
)。选择TextBox
后(IsKeyboardFocused==true
时),我希望格式化消失,直到TextBox
的焦点丢失为止。
我找到了一种方法,下面粘贴代码。我的问题是绑定是在Style
中指定的 - 这意味着我必须为每个TextBox
重新键入我想要执行此操作的样式。我希望将样式置于中心位置,并为每个TextBox
重复使用它,并为每个{{p}}设置不同的绑定目标。
我是否可以使用Style
在现有绑定上设置参数,例如Text.Binding.StringFormat=""
? (与将Text的整个值设置为新定义的Binding相反)
其他建议也是值得赞赏的。
代码(这很有用,只是不方便):
<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>
答案 0 :(得分:6)
使用附加属性是可行的,但这意味着您必须完全替换绑定,然后将其放回去。
这是一个快速而肮脏的实现:
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
}
用法:
<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>
使用此功能,您还可以将样式重用于不同的TextBoxes