我有 1234 值,我必须将其显示为 0012:34,当用户单击该文本框以编辑该值时,它应该只显示 1234,当标签退出时它应该返回到 0012:34。如果我使用转换器,它在获得焦点时不会改变格式。我在数据模板中有这个文本框,也无法在后面的代码中访问它,这意味着我无法在 Got_Focus 事件中进行格式化。有人可以帮忙格式化吗?我可以使用 int 或 string 作为数据类型。
谢谢,罗西
我有 1234 值,我必须将其显示为 0012:34,当用户单击该文本框以编辑该值时,它应该只显示 1234,当标签退出时它应该返回到 0012:34。如果我使用转换器,它在获得焦点时不会改变格式。我在数据模板中有这个文本框,也无法在后面的代码中访问它,这意味着我无法在 Got_Focus 事件中进行格式化。有人可以帮忙格式化吗?我可以使用 int 或 string 作为数据类型。
谢谢,罗西
您可以使用扩展WPF 工具包中的WatermarkTextBox:
<xctk:WatermarkTextBox Text="{Binding Value}" Watermark="{Binding Value, Mode=OneWay, Converter={StaticResource YourValueConverter}}" />
作为水印文本框的替代方案,您可以使用行为。
System.Windows.Interactivity需要参考。
例子:
xml:
<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);
        }
    }
}