WPF - C# Desktop App - Condition, if textbox integer value is 0 than background red and content should be empty.

Markus Freitag 3,786 Reputation points
2020-07-29T11:11:05.373+00:00

14294--2.png

14295--no-ok.png

Hello,
the goal is.
If the value == 0 then backgroundcolor red and empty not zero.

Can I use a converter to handle two conditions?

My idea was via Trigger, but it is not work. Why?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,679 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-07-30T08:25:53.177+00:00

    Hi Markus,
    you can use Converter.

      public class ViewModel  
      {  
        public int Value { get; set; } = 0;  
      }  
      public class TextBoxConverter : IValueConverter  
      {  
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
        {  
          if (targetType == typeof(Brush))  
            return (value.GetType() == typeof(int) && (int)value == 0) ? Brushes.Red : Brushes.White;  
          return (targetType == typeof(string) && (int)value == 0) ? "" : value.ToString();  
        }  
      
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>  
          (value == null || string.IsNullOrEmpty(value.ToString())) ? 0: value;  
      }  
    

    14573-x.png

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-07-30T03:34:37.82+00:00

    You can try the below style for the TextBox:
    14405-20-07-20-112018.jpg

    1 person found this answer helpful.

  2. Markus Freitag 3,786 Reputation points
    2020-07-30T08:21:28.983+00:00

    I think the solution is, for each property I can use a converter.
    How is your opinion?

    14338--maybe.png

    0 comments No comments