2012-10-31 41 views
3

我有1234的值,我必須將它顯示爲0012:34,當用戶單擊該文本框編輯值時,它應該只顯示1234,它應該回到0012:34。如果我使用轉換器,它在獲得焦點時不會更改格式。我在數據模板中有這個文本框,並且無法在後面的代碼中訪問它,也就是說,我無法在Got_Focus事件中進行格式設置。任何人都可以幫助格式化嗎? 我可以使用int或字符串作爲數據類型。wpf字符串格式整數1234到12:34只在XAML中

感謝, 玫瑰

回答

0

您可以使用WatermarkTextBoxExtended WPF Toolkit

<xctk:WatermarkTextBox Text="{Binding Value}" Watermark="{Binding Value, Mode=OneWay, Converter={StaticResource YourValueConverter}}" /> 
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); 
     } 
    } 
} 
相關問題