简体   繁体   中英

How to handle Empty Uri's for Path Binding to an Image Source

how can I initialize an Uri object in an empty state.

First thought would be to do something like this

//does not work
Uri myUri = Uri.Empty

This one does also not work

Uri myUri = new Uri(string.Empty)

The reason is I store my image path in the db and in case there is no image defined I have a blank database record.

I know that there are ways to handle this with a converter and return a default blank image Uri in case the image_path is empty...

How do I handle the binding to my ViewModel Uri Property best?

Is the converter the way to go and how do you handle it if you would have like many different default images which should be returned...

Just set:

new Uri("about:blank");

Works for me.

You can do something like this

Uri uri = null;
bool someValue = Context.TryGetUri(entity, out uri);

Other way to handle this is you can alter your data query for example if you are using from sql employees table then you could write as like below.

select Employeeid, FirstName, LastName, 
case when ImageUrl is null then 'http://www.codeodor.com/images/Empty_set.png' else ImageUrl end as ImageUrl from employees

this will handle the null and return an default url for the empty image;

hope it suits you.

I have the same problem and after thinking a while I believe there isn't a default constructor for System.Uri because it doesn't make sense. Indeed, an URI identifies a resource, therefore if the resource doesn't exist or cannot be located, I think the best approach is to deal with a null reference instead of an empty Uri .

In your code, instead of having (pseudo-code):

if (myUri != Uri.Empty)
{
    // do something
}

you'll have:

if (myUri != null)
{
   // do something
}

In this case you can use also the Null-conditional Operator , if it fits your workflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM