Setting String as Image Source in C#
Well I've looked up several methods to fix this in my Windows Phone 7 app but I can't seem to find anything that works. What confuses me is that I've done something just like this before with no problem, so I'm not sure why it's not working. The code causing me the problem is this:
if (appSettings.Contains("image")) 开发者_开发知识库 myImage.Source = (string)appSettings["image"]; else myImage.Source = "default.jpg";The error I get is this
Cannot implicitly convert type 'string' to 'System.Windows.Media.ImageSource.
The reason this confuses me is because I did this Twitter app tutorial, in which you bind the image source directly to a string. So what can I do to fix this?
You need to specify an ImageSource instead of a string when doing it from code:
Uri uri = new Uri("...", UriKind.Absolute);
ImageSource imgSource = new BitmapImage(uri);
myImage.Source = imgSource;
Unless I've not found the right part of Scott's post that you're looking at, he is binding image source to a url.
Specificaly,
ImageSource = tweet.Element("user").Element("profile_image_url").Value
Which would be something like
http://a0.twimg.com/profile_images/1158022545/mickn_normal.jpeg
Let me explain my solution regarding this topic. I just created a setting in the settings. Every configuration that you set here, will be shown in the App.config file too.
Settings
Settings2
After you've successfully configured the Image's path in the settings, you just have to get the source in the MainWindows.xaml.cs file.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string ImagePath = Properties.Settings.Default.ImagePath;
Uri resourceUri = new Uri(@ImagePath,UriKind.RelativeOrAbsolute);
MainImage.Source = new BitmapImage(resourceUri);
}
}
I hope this can help you a bit.
精彩评论