Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a custom Binding

Tags:

.net

binding

wpf

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);
}
like image 220
serhio Avatar asked May 07 '26 13:05

serhio


1 Answers

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).

like image 62
Dan Bryant Avatar answered May 09 '26 02:05

Dan Bryant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!