Search code examples
wpftextblock

WPF Replace value in TextBlock


Lets say i have a TextBlock thats bound to a DateTime, is there any way to replace the value 0001-01-01 00:00:00 with an empty string?


Solution

  • You have a few options:

    1. Bind to a DateTime? (that is, Nullable<DateTime>) rather than DateTime. Set the value to null when you want nothing to appear.
    2. Bind to a separate property on your view model which is responsible for converting DateTime.MinValue to an empty string.
    3. Bind directly to the DateTime property and use a converter to convert DateTime.MinValue to an empty string.

    Example of #1

    <TextBlock Text="{Binding SomeDateTime}"/>
    
    public class YourViewModel : ViewModel
    {
        private DateTime? _someDateTime;
    
        public DateTime? SomeDateTime
        {
            get { return _someDateTime; }
            set
            {
                if (_someDateTime != value)
                {
                    _someDateTime = value;
                    OnPropertyChanged("SomeDateTime");
                }
            }
        }
    }
    

    Example of #2

    <TextBlock Text="{Binding SomeDateTimeString}"/>
    
    public class YourViewModel : ViewModel
    {
        private DateTime _someDateTime;
    
        public DateTime SomeDateTime
        {
            get { return _someDateTime; }
            set
            {
                if (_someDateTime != value)
                {
                    _someDateTime = value;
                    OnPropertyChanged("SomeDateTime");
                    OnPropertyChanged("SomeDateTimeString");
                }
            }
        }
    
        public string SomeDateTimeString
        {
            get { return SomeDateTime == DateTime.MinValue ? "" : SomeDateTime; }
        }
    }
    

    Example of #3

    <!-- in resources -->
    <local:DateTimeConverter x:Key="YourConverter"/>
    
    <TextBlock Text="{Binding SomeDateTime, Converter={StaticResource YourConverter}}"/>
    
    public class YourClass
    {
        private DateTime _someDateTime;
    
        public DateTime SomeDateTime
        {
            get { return _someDateTime; }
            set
            {
                if (_someDateTime != value)
                {
                    _someDateTime = value;
                    OnPropertyChanged("SomeDateTime");
                }
            }
        }
    }
    
    public class DateTimeConverter : IValueConverter
    {
        public object Convert(object value ...)
        {
            return value == DateTime.MinValue ? "" : value;
        }
    
        ...
    }