Stampy
Stampy

Reputation: 466

Binding WPF return default string

I want to bind the object Info in my xaml column:

<DataGridTextColumn Width="200" Binding="{Binding Path=Message.Info.InfoName, Mode=OneWay, TargetNullValue=No Information available}">
    <DataGridTextColumn.Header>
        <Label>Information</Label>
    </DataGridTextColumn.Header>
</DataGridTextColumn>

For each message I've a constructor and in the same message class I've this property:

public IMessageInformation Info
{
    get
    {
        //if (_info == null)
        //  return "no info available";
        return _info;
    }

    set
    {
        _info = value;
        NotifyPropertyChanged("Info");
    }
}

Now, for each message the WPF column should display either the name of the information (gets from the object Info (Info.InfoName property)) or if the message has no information (other type) it should display "No Info available".

If there is no information available I get no object (Info == null).


My problem:


What I've tried:

I've tried to insert an if statement into the Info property (getter). The statement works but of course I can't return a string if the property expects the return type object info.

And my other approach TargetNullValue=No Information available} doesn't work too.

Upvotes: 1

Views: 228

Answers (2)

galenus
galenus

Reputation: 2137

You should add a FallbackValue attribute to your XAML like this:

Binding="{Binding
    Path=Message.Info.InfoName,
    Mode=OneWay,
    FallbackValue=No Information available}"

This is because your binding fails due to the fact that the Info part in your binding path is null. You should see a matching error in your debug output.

Upvotes: 3

Alex
Alex

Reputation: 626

Depends a bit on how you fetch the data but one solution could be to have an "InfoName" property on the message which you populate when you fetch the data.

List<Message> messages = context.Messages.Select(m => new Message
{
    InfoName = m.Info != null ? m.InfoName : "no info available",
    // etc.
})
.ToList();

Upvotes: 0

Related Questions