Custom Binding Implementation

I have MyUserControlone that contains a label labeland BO public Person Person {get;set;}.

I want Person to Namealways contact the labelfollowing:

( "Name: {0}", person.Name) if person != null
and
( "Name: {0}", "(none)") ifperson == null

moreover, if a person’s name is changed, the tag will automatically update it.

is there a possibility of such a binding?

"Dirty" option:

private void label_LayoutUpdated(object sender, EventArgs e)
{
    label.Content = string.Format("Name: {0}", _Person == null ? 
                                                      "(none)" : _Person.Name);
}
+3
source share
3 answers

What about:

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Name: "/>
        <TextBlock Text="{Binding Person.Name, FallbackValue='(none)'}"/>
    </StackPanel>

It does not use the shortcut, but it fulfills the purpose.


If it should be a label, you can do this:

    <Label Content="{Binding Person.Name, FallbackValue='(none)'}" 
           ContentStringFormat="Name: {0}"/>

, Name: (none), (Person == null - Person found).

+3

.

[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();
    }
}

, XAML:

<local:PersonNameConverter x:Key="PersonNameConverter"/>

<TextBlock  
    Text="{Binding Path=ThePerson, Converter={StaticResource PersonNameConverter}}" 
    />
+1

Use the Binding FallBackValue Property

        <Lable Content ="{Binding Person.Name, FallbackValue='(none)'}"/> 
0
source

Source: https://habr.com/ru/post/1777809/


All Articles