私はこのようなプロパティを持っています (int のように nullable にしたくありませんか?)
public int id{get;set;}
id プロパティにバインドされた TextBox があります
<TextBox Text="{Binding id}"/>
私のウィンドウが読み込まれたとき、TextBox の値が 0 になっています。TextBox から ID のデフォルト値を非表示にするにはどうすればよいですか
次のようなバインディング コンバーターを使用できます。
[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 = 0の場合にのみ非表示にしたい場合は、トリガーを使用する必要があります
同じグリッド内で空の文字列を持つ別の TextBox を使用し、最初の TextBox のデフォルト値が 0 のときに表示することができます。
<Grid>
<TextBox Text="{Binding id}" x:Name="txtbox1"/>
<TextBox Text="" Visibility="{Binding Text,ElementName=txtbox1,Converter={StaticResource StringToVisibility}}"
</Grid>
使用した Converter に基づく上記のコードでは、テンプレートで動作します。テキストに「0」が付いている場合は、2番目の 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();
}
}
int を使用する代わりに、ここで string を ID として使用し、独自の検証を記述できます。またはintを使用できますか?intの代わりに。
public int? id{get;set;}
EDIT id フィールドを nullable に変更したくない場合は、文字列にバインドするか、コンバーターを使用するだけですが、いずれにしても、IDataErrorInfoを実装して独自の検証を実装する必要があります。