I’ve recently started experimenting with DataBinding and implementing DependencyProperties for my custom classes. It all works fine and the possibilities are exciting, however, I came across a problem that may be only solvable by slightly modifying the overall class design. And I want to make sure this is the only option and I’m not missing anything.
So, my class stores information about video files the user imports into the application. Among other properties, it contains:
public class VideoFile {
public string FilePath { get; protected set; }
public uint ID { get; protected set; ]
public string Extension { get { return Path.GetExtension(FilePath); } }
public string FileName { get { return Path.GetFilename(FilePath); } }
}
So, I’ve successfully replaced FilePath with an DependencyProperty. However, in the UI, I mostly want to display just the filename, which uses some logic to provide its value. As far as I know, here are my options:
- I could simply create DependencyProperties for FileName and Extension, and set their value in the constructor, but that’s redundant; I already have that information in the FilePath, so I want to avoid this option.
- Create ValueConverters, one for displaying Filename and one for displaying Extension, and use them in my bindings.
I’ve only met ValueConverters briefly, so I’m not sure about it. Can I use them for this purpose? Or, have I just encountered one of the main reasons they exist? 🙂
And last but not least, can anyone think of a situation similar to this, when a ValueConverter is not the right way to go? I want to avoid jumping straight into them, only to realize it will not work because “that one” property just can’t be expressed in this way.
Don’t duplicate data.
Prefer
Bindingand anIValueConverter, because that way, wheneverFilePathchanges,ExtensionandFileNamewill be updated in the UI as well.You could also, of course, raise
PropertyChangedfor them inFilePath‘s setter but that’s bad practice sinceFilePathshould not have to care about who/what uses it.The class then looks like:
Please note that
PropertySupportis part of Prism, but you can do without it by callingRaisePropertyChanged("FilePath"), it’s just neat to have type safety because if you change the property’s name you will have a compile-time error.