开发者

WPF Non-Nullable Databinding to default a cleared TextBox?

开发者 https://www.devze.com 2022-12-20 13:42 出处:网络
I have a WPF TextBox, with the Text property bound to an int value (non nullable).When the form loads, the text box has a 0 in it.Is there any way to make this textbox default to empty?

I have a WPF TextBox, with the Text property bound to an int value (non nullable). When the form loads, the text box has a 0 in it. Is there any way to make this textbox default to empty?

I was setting the value to null in the code behind when the form loads, but it seems that in places, this is throwing errors that are being hidden to me, since null cannot go into the int value.. Is that bad practice? I have lots of the开发者_C百科se situations, DateTime's being set, and when the screen loads, the date is 1/1/0001, which is ugly to a user. I can default the date to todays date, but in some cases, like birthdate, that doesn't make sense.


You should make your Binding one-way, using BindingMode=OneWayToSource. See MSDN for details.


You can use a value converter (see IValueConverter), or expose the int as a string from your view model:

public string Value
{
    get
    {
        if (intValue == 0)
        {
            return string.Empty;
        }

        return intValue.ToString();
    }
    set
    {
        // do conversion here
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号