IValueConverter set new image

336 Views Asked by At

Hi to all out there...

I facing one problem which is cannot set the new image:

Does my code correct?

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            var str = value.ToString();

            if (str == "income")
                return new BitmapImage(new Uri("/images/add.png", UriKind.Relative));

            if (str == "Expenses")
            {

                return new BitmapImage(new Uri("/HouseWivesSavior;component/images/add.png"));
            }

            return null;
        }
2

There are 2 best solutions below

1
On

You have to make sure that the image files have their Build Action set to Resource as shown for example here. Then you would have to properly create their Pack URIs, like

return new BitmapImage(new Uri("pack://application:,,,/images/add.png"));

and

return new BitmapImage(
    new Uri("pack://application:,,,/HouseWivesSavior;component/images/add.png"));
0
On

I found the solution for my answer which is the format of the string. Which causing me to unavailable to retrieve the image with few hours of troubleshooting & debugging. I finally found out the solution :)

I solve it by like this:In my converter.cs

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {

string str = (string)value;
string newString = str.TrimEnd();//Newly added compared with the old version

if (newString == "income")
   return new BitmapImage(new Uri("pack://application:,,,/images/add.png"));

if (newString == "Expenses")
{
    //return new BitmapImage(new Uri(@"pack://application:,,,/HouseWivesSavior;component/images/add.png"));
    return new BitmapImage(new Uri("pack://application:,,,/images/edit.png"));
}

return null;

}

From referring the above that you can see that I added this code: "string newString = str.TrimEnd();"

Is because I don't want extra white space at the end of the string. As during insert into the database that my code is look like this:

   if (IncomeButton.IsChecked == true) {
                    CategoryType = IncomeButton.Content.ToString();
                }else{
                    CategoryType = ExpensesButton.Content.ToString();
                }

During runtime, I found out that why the value look strange in the format of "Expenses " instead of "Expenses"... Therefore I tried with trim of the end part see how & Bingo. I got it working like a charm.

I refered this video to out that how to trace the value: http://www.youtube.com/watch?v=evO3_xutDYI

Thank you all guys for answering my question & sorry for wasting your time & effort to solve my question :) Good luck to all of you & have a nice day.