2012-07-16 51 views
0

我有這樣一個屬性(我不希望它可以爲空如int?)如何隱藏屬性在我的控件中的默認值?

public int id{get;set;} 

我有一個綁定到id屬性

<TextBox Text="{Binding id}"/> 

當我的窗口加載一個TextBox我文本框有值0,我怎麼能隱藏我的文本框

+0

你是什麼意思?隱藏文本框?或者當它是0時放置一個特殊的文本? – MBen 2012-07-16 11:04:54

+0

只需將ID字段更改爲空即可 – 2012-07-16 11:14:03

+0

@KishoreKumar我不想將ID字段更改爲可空 – 2012-07-16 11:27:50

回答

1

你可以使用一個binding converter這樣的:

[ValueConversion(typeof(int), typeof(string))] 
public class IntegerConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     int intValue = (int)value; 
     return intValue != 0 ? intValue.ToString() : string.Empty; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     int intValue = 0; 
     int.TryParse((string)value, out intValue); 
     return intValue; 
    } 
} 
1

設置visibility屬性崩潰ID默認值,或隱藏

或者如果你的意思是你只想隱藏它當ID = 0,那麼你應該使用觸發器

0

而不是使用整型,你可以在這裏使用字符串作爲你的ID並寫你自己的驗證。或者你可以使用int?而不是int。

public int? id{get;set;} 

編輯 如果你不想id字段被更改爲空的,不僅僅是綁定到一個字符串或使用一個轉換器,但無論哪種方式,您將需要通過實施來實現自己的驗證IDataErrorInfo

+0

我不想將id字段更改爲可空 – 2012-07-16 11:27:03

0

您可以使用另外一個文本框與空字符串相同的網格內,並使其可見,當第一個TextBox具有默認值爲0。

<Grid> 
    <TextBox Text="{Binding id}" x:Name="txtbox1"/> 
    <TextBox Text="" Visibility="{Binding Text,ElementName=txtbox1,Converter={StaticResource StringToVisibility}}" 
</Grid> 

在上面的代碼基於我們所使用的轉換器,它將在模板中工作。您必須在轉換器中寫入文本帶有「0」時,只需使第二個文本框可見即可。

public class StringToVisibility : IValueConverter 
    { 
     public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      string str = value.ToString(); 
      if (str.Equals("0")) 
      { 
       return Visibility.Visible; 
      } 
      return Visibility.Collapsed; 
     } 

     public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new System.NotImplementedException(); 
     } 
    } 
+0

當用戶在'textbox1'中輸入'0'時會發生什麼? – Bolu 2012-07-17 13:40:51

+0

只要它將第二個文本框與空字符串放在txtbox1上。所以它會自動隱藏第一個.. – 2012-07-17 14:11:30