I had a case where there were a set of notices on the side of a
Window, and wanted to hide a control when there were no notices. I was initially puzzled on how to do this, but fortunately, the
ObservableCollection has a
Using the Code
I have used some of the classes I developed in creating a flexible
IValueConverter, the article describing these classes and code sample is here. This just made it easier, and I think that the converters and helper class described in this article are an excellent addition to any WPF project, and I think that using these converters makes the code much easier to read. I also inherit from
MarkupExtension on my converters because it means that I can use the converters directly without first declaring them in XAML. Here is the XAML I use to Bind the
Visibility property of the control that I want to hide if there are elements in a collection:
Text="No names added"
As can be seen, the
Path I use is the
Count property of the
Names. You can also see that because the
IsEqualConverter is derived from
MarkupExtension, I am able to specify the
Converter with just
ConverterParameter specifies the condition, which is the "
0" before the "
?" mark, and if that the value of
Count is equal to that condition, then the first value after the "
?" is used (
Visible), otherwise the value after the "
:" is used (
The sample has an
TextBlock on the right hand side of the
Window, both filling up the whole right side. The
TextBlock, which has the
Text "No names added", and has its
Visibility bound to the
Count property of the
ObservableCollection bound to the
Converter converts the
Count to a
Visiblity.Visible if the
Count value is
0, and a
Visibility.Collapsed otherwise. In this case, the
ConverterParameter contains information for the specific convert that this property is bound to necessary to determine the
IValueConverter returns and on what conditions that
IValueConverter returns each.
To use the sample, just add a name into the
TextBox and click the "Add Name"
Button. This will add the name to the items collection which cause the text "No names added" to disappear, and the name to appear in the
ItemsControl. The "Delete Name"
Button can be clicked to remove the name from the collection and the "No names added" text will reappear.
- 08/11/17: Initial version
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at email@example.com.