开发者

Implementing a custom Binding

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开发者_Python百科 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);
}


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


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}}" 
    />


Use Binding FallBackValue property

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜