wpf字符串格式仅在XAML中为整数1234到12:34

时间:2012-10-31 00:43:20

标签: wpf string-formatting

我有1234的值,我必须将其显示为0012:34,当用户点击该文本框来编辑值时,它应该只显示1234,当选项卡显示时它应该返回到0012:34。如果我使用转换器,它在获得焦点时不会改变格式。我在数据模板中有这个文本框,也无法在后面的代码中访问它,这意味着,我无法在Got_Focus事件中进行格式化。有人可以帮忙格式化吗? 我可以使用int或string作为数据类型。

谢谢, 红润

2 个答案:

答案 0 :(得分:0)

您可以使用WatermarkTextBox中的Extended WPF Toolkit

<xctk:WatermarkTextBox Text="{Binding Value}" Watermark="{Binding Value, Mode=OneWay, Converter={StaticResource YourValueConverter}}" />

答案 1 :(得分:0)

作为水印文本框的替代方案,您可以使用行为。

需要引用

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);
        }
    }
}