[英]How to hide a property Default value in my control?
我有這樣的屬性(我不希望它像int一樣可以為空?)
public int id{get;set;}
我有一個綁定到id屬性的TextBox
<TextBox Text="{Binding id}"/>
當我的Windows加載我的TextBox的值為0時,如何隱藏我的TextBox中的id默認值
將visibility屬性設置為折疊或隱藏
或者如果你的意思是你只想在id = 0時隱藏它,那么你應該使用一個觸發器
您可以使用這樣的綁定轉換器 :
[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;
}
}
您可以在此處使用字符串作為您的ID,而不是使用int,並編寫自己的驗證。 或者你可以使用int? 而不是int。
public int? id{get;set;}
編輯如果您不希望將id字段更改為可空,而不僅僅是綁定到字符串或使用轉換器,但無論哪種方式,您都需要通過實現IDataErrorInfo來實現自己的驗證。
您可以在同一網格中使用另一個帶有空字符串的TextBox,並在第一個TextBox的默認值為0時使其可見。
<Grid>
<TextBox Text="{Binding id}" x:Name="txtbox1"/>
<TextBox Text="" Visibility="{Binding Text,ElementName=txtbox1,Converter={StaticResource StringToVisibility}}"
</Grid>
在上面基於我們使用的Converter的代碼中,它將在模板中工作。 你必須在轉換器中寫入當文本帶有“0”時,只需使第二個TextBox可見即可。
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.