Reputation: 3583
I have a collection of objects that I wish to bind to a ListView control. In some of the objects, the value of a property that will be displayed in a column in the ListView is an empty string (""). I want to replace the empty string ("") with "n/a" automatically using binding.
How can I accomplish this?
Upvotes: 0
Views: 1365
Reputation: 292345
Use the BindingBase.TargetNullValue property :
<GridViewColumn DisplayMemberBinding="{Binding MyProperty, TargetNullValue=N/A}"/>
EDIT: as pointed out by Aviad, this will only work for a null value, not an empty string. I don't delete this answer because it can still be useful to others.
Upvotes: 1
Reputation: 32629
Define a value converter:
class EmptyToN_AConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
string s = value.ToString();
if (string.IsNullOrEmpty(s)) return "N/A";
return s;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Example XAML:
<Window.Resources>
...
<local:EmptyToN_AConverter x:Key="NAConverter"/>
</Window.Resources>
...{Binding Path=TheProperty, Converter={StaticResource NAConverter}}...
You may even parameterize the converter and expose the "N/A" in XAML:
public object Convert(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
string s = value.ToString();
if (string.IsNullOrEmpty(s)) return parameter.ToString();
return s;
}
...{Binding Path=TheProperty,
Converter={StaticResource NAConverter},
ConverterParameter=N/A}...
Upvotes: 3
Reputation: 29120
public string MyProperty
{
get
{
if (String.IsNullOrEmpty(_myProperty))
return "n/a";
else
return _myProperty;
}
set
{
if (_myProperty != value)
{
_myProperty = value;
RaisePropertyChanged("MyProperty")
}
}
}
Upvotes: 0
Reputation: 746
You could always add a read only property to your bound object that formatted what you wanted to display.
public string Property
{
get;
set;
}
public string PropertyDescriptor
{
get
{
if (string.IsNullOrEmpty(this.Property))
return "n/a";
else
return this.Property;
}
}
This works quite well if you're using MVVM.
Upvotes: 1