我有1234的值,我必须将它显示为0012:34,当用户单击该文本框编辑值时,它应该只显示1234,它应该回到0012:34。如果我使用转换器,它在获得焦点时不会更改格式。我在数据模板中有这个文本框,并且无法在后面的代码中访问它,也就是说,我无法在Got_Focus事件中进行格式设置。任何人都可以帮助格式化吗? 我可以使用int或字符串作为数据类型。wpf字符串格式整数1234到12:34只在XAML中
感谢, 玫瑰
我有1234的值,我必须将它显示为0012:34,当用户单击该文本框编辑值时,它应该只显示1234,它应该回到0012:34。如果我使用转换器,它在获得焦点时不会更改格式。我在数据模板中有这个文本框,并且无法在后面的代码中访问它,也就是说,我无法在Got_Focus事件中进行格式设置。任何人都可以帮助格式化吗? 我可以使用int或字符串作为数据类型。wpf字符串格式整数1234到12:34只在XAML中
感谢, 玫瑰
您可以使用WatermarkTextBox从Extended WPF Toolkit:
<xctk:WatermarkTextBox Text="{Binding Value}" Watermark="{Binding Value, Mode=OneWay, Converter={StaticResource YourValueConverter}}" />
作为一种替代你可以使用行为水印文本框。
System.Windows.Interactivity
需要引用。
实施例:
的Xaml:
<Window x:Class="WatermarkTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:WatermarkTextBox="clr-namespace:WatermarkTextBox" Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Width="300" Height="30">
<i:Interaction.Behaviors>
<WatermarkTextBox:WatermarkBehavior />
</i:Interaction.Behaviors>
</TextBox>
<TextBox Grid.Row="1" Width="300" Height="30" />
</Grid>
</Window>
行为:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace WatermarkTextBox
{
public class WatermarkBehavior : Behavior<TextBox>
{
private string _value = string.Empty;
protected override void OnAttached()
{
AssociatedObject.GotFocus += OnGotFocus;
AssociatedObject.LostFocus += OnLostFocus;
}
protected override void OnDetaching()
{
AssociatedObject.GotFocus -= OnGotFocus;
AssociatedObject.LostFocus -= OnLostFocus;
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
AssociatedObject.Text = _value;
}
private void OnLostFocus(object sender, RoutedEventArgs e)
{
_value = AssociatedObject.Text;
AssociatedObject.Text = string.Format("Watermark format for: {0}", _value);
}
}
}