2013-02-05 32 views
0

我想創建一個文本框/ IValueConverter,如果用戶點擊1234,然後退格3次,將向用戶顯示以下行。用IValueConverter屏蔽文本框輸入而不丟失數據

1 
*2 
**3 
***4 
*** 
** 
* 

我最大的那一刻問題是,我失去的數據作爲的IValueConverter在我的ViewModel節約「*** 4」。

是否有任何常見的策略來掩蓋像這樣的輸入數據而不使用普通的PasswordBox?

+0

使用這項工作的正確控制。 [PasswordBox](http://msdn.microsoft.com/en-us/library/system.windows.controls.passwordbox(v = vs.110).aspx) – Will

回答

0

您可以創建一個虛擬的TextBlockLabel來顯示蒙版,並將TextBox文本顏色設置爲透明。這樣實際的數據被保存到模型中,並且*只顯示在標籤中。

喜歡的東西(很粗糙的例子)

<Window x:Class="WpfApplication13.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication13" 
     Title="MainWindow" Height="350" Width="525" Name="UI"> 
    <Window.Resources> 
     <local:TextToStarConverter x:Key="TextToStarConverter" /> 
    </Window.Resources> 
    <StackPanel> 
     <Grid> 
      <TextBox x:Name="txtbox" Foreground="Transparent" Text="{Binding MyModelProperty}" /> 
      <Label Content="{Binding ElementName=txtbox, Path=Text, Converter={StaticResource TextToStarConverter}}" IsHitTestVisible="False" /> 
     </Grid> 
    </StackPanel> 
</Window> 

轉換器(pleae忽略可怕的代碼,它只是一個演示:))

public class TextToStarConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value is string && !string.IsNullOrEmpty(value.ToString())) 
     { 
      return new string('*', value.ToString().Length -1) + value.ToString().Last().ToString(); 
     } 
     return string.Empty; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 
} 

結果:

enter image description here

+0

謝謝sa_ddam213,這是我的第一個方法,但因爲它不使用文本框內部的ContentPresenter沒有顯示carot。 –

+0

插入符號將以此方法顯示,因爲我們只將forground設置爲Transparent而不是插入符號筆刷。看到我的圖像更新。我沒有覆蓋我剛剛覆蓋頂部的一個標籤的文本框的樣式。 –