Reputation: 28586
I have a MyUserControl
that contains a Label label
, and a BO public Person Person {get;set;}
.
I want that the Person's Name
be always bind to the label
like this:
("Name: {0}", person.Name
), in case if person != null
and
("Name: {0}", "(none)"
), in case if person == null
more than that, if the person name is changed, the label automatically update it.
is there a possibility for such a binding?
"Dirty" variant:
private void label_LayoutUpdated(object sender, EventArgs e)
{
label.Content = string.Format("Name: {0}", _Person == null ?
"(none)" : _Person.Name);
}
Upvotes: 3
Views: 102
Reputation: 17556
Use Binding FallBackValue property
<Lable Content ="{Binding Person.Name, FallbackValue='(none)'}"/>
Upvotes: 0
Reputation: 27495
How about:
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Person.Name, FallbackValue='(none)'}"/>
</StackPanel>
This doesn't use a Label, but it accomplishes the goal.
If it needs to be a Label, you can do this:
<Label Content="{Binding Person.Name, FallbackValue='(none)'}"
ContentStringFormat="Name: {0}"/>
One caveat with both approaches is that the text will also display Name: (none)
if the binding is incorrect (Person == null is equivalent behavior to no property Person found).
Upvotes: 3
Reputation: 45222
This problem can be solved by writing a value converter.
[ValueConversion(typeof(Person), typeof(String))]
public class PersonNameConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Person person = value as Person;
if(person == null)
{
return "(none)";
}
else
{
return person.Name;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Once you have created this, you can add it as a resource in the XAML:
<local:PersonNameConverter x:Key="PersonNameConverter"/>
Then this can be included as one of the binding parameters
<TextBlock
Text="{Binding Path=ThePerson, Converter={StaticResource PersonNameConverter}}"
/>
Upvotes: 1