I'm trying to change my image source and some text in a textblock, the source comes from a class that is returned from a WCF service and is in a String format, when i use some functions in my code, images and text will update, but if i try to update it right before a Thread.Sleep it won't change, same for the textblock
Here's the problematic code:
//ris is the class returned from the server
image.Source = new BitmapImage(new Uri("Res/" + ris.carta + ".png", UriKind.Relative));
if (ris.IDv == ID)
{
puntiuno += ris.punti;
txtb_info.Text += "\nHai vinto la mano!";
mano.Add(ricevicarte(2)[0]);
V = true;
}
else
{
txtb_info.Text += "\nHai perso la mano!";
puntidue += ris.punti;
mano.Add(ricevicarte(2)[0]);
V = false;
}
//Secondacarta(ris.carta);
System.Threading.Thread.Sleep(5000);
aggiornainterfaccia();
txtb_info.Text += "\nNuova mano!";
blocco = 0;
everything that comes after the Thread.Sleep works, every WPF controls update i try before won't work
Here's the "aggiornainterfaccia()" code:
private void aggiornainterfaccia()
{
ris = null;
carta1_img.Source = new BitmapImage(new Uri("Res/" + mano[0] + ".png", UriKind.Relative));
carta2_img.Source = new BitmapImage(new Uri("Res/" + mano[1] + ".png", UriKind.Relative));
carta3_img.Source = new BitmapImage(new Uri("Res/" + mano[2] + ".png", UriKind.Relative));
image.Source = new BitmapImage(new Uri("Res/dorso.png", UriKind.Relative));
txt_punti_p1.Text = "Punti: " + puntiuno.ToString();
txt_punti_p2.Text = "Punti: " + puntidue.ToString();
txtb_info.Text = "";
if (V)
{
lbl_mano.Content = "Sei di mano!";
}
else
{
lbl_mano.Content = "Non sei di mano!";
}
}
this is called right after the delay and it works and its function is to reset the interface to a initial state
Related
I' m trying to resolve error cs1010 newline in constant.
At this Line
if ((image1.Source==new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))) &&(objNameWritten1.Text==objnamewritten[LI]))
The output is"ms-appx:///Assets/LearnColor/Object/ob_0"
but it should be
"ms-appx:///Assets/LearnColor/Object/ob_0_0"
Where is the Error Exactly
Cs code
private void common()
{
if (CI > 10)
{
CI = 0;
return;
}
if (HeaderName.Text== Headername[CI])
{
int LI = 0;
for (int i = 3*CI+LI; i < 3*(CI+1); LI++)
{
if ((image1.Source==new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))) &&(objNameWritten1.Text==objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
else if ((image2.Source == new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png"))) && (objNameWritten2.Text == objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
else if ((image3.Source == new BitmapImage(new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png"))) && (objNameWritten3.Text == objnamewritten[LI]))
{
ppup.Height = Window.Current.Bounds.Height;
ppup.IsOpen = true;
CI++;
HeaderName.Text = Headername[CI];
common();
}
}
}
else
{
ppup1.Height = Window.Current.Bounds.Height;
ppup1.IsOpen = true;
}
I have tested your code on my side. There is nothing wrong with string concat. The uri result is ms-appx:///Assets/LearnColor/Object/ob_0_0.png which is right. Here is the screenshot of the result. You can also print out your concat result as following picture shows.
The error actually for your if condition is that you compare a BitmapImage with ImageSource in your code snippet. For judging whether the ImageSource is equal with one picture, you can use code as follows:
if((image1.Source as BitmapImage).UriSource== new Uri("ms-appx:///Assets/LearnColor/Object/ob_" + CI + "_" + LI + ".png", UriKind.Absolute))
I'm trying to scroll through images in my app, but I'm having trouble figuring out how to populate my list. The images are named using numbers from 1.jpg upwards. If anyone could help it would be great.
async private void Exec()
{
// Get the file location.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string myImageFolder = (appFolder.Path + "\\Assets\\Images");
int imageNumber = 1;
List<Uri> fileList = new List<Uri>();
foreach (var fileItem in fileList)
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(myImageFolder + "/" + imageFileName);
fileList.Add(uri);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
imageNumber++;
}
}
UPDATE
I have tried to create a workaround and do this without the foreach statement but its crashing when testing if the next file exists: :(
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
Uri uri1 = new Uri(path + "\\" + testFile);
if (await appFolder.TryGetItemAsync(uri1.ToString()) != null)
{
test = 99999;
}
}
while (test != 99999);
}
Your list does not contain any items. Your foreach will never run, as there will be no entries in your list.
You need to go through all paths in myImageFolder-root and add those uris to the list, then you can just use them in a foreach to create images and set their source, for every uri in the list.
Also imageNumber is un-needed then as you will have the URIs.
Prep the list of URIs first, by traversing the folder. Then modify the existing foreach to use those to build image objects.
Also, refrain from adding to a collection WHILE iterating it...
I have this working, and not a single foreach was required :D Thanks #Richard Eriksson
async private void Exec()
{
// Get the file location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path);
int imageNumber = 1;
int test = imageNumber;
do
{
string imageFileName = imageNumber + ".jpg";
Uri uri = new Uri(path + "\\" + imageFileName);
image.Source = new BitmapImage(new Uri(uri.ToString()));
await Task.Delay(TimeSpan.FromSeconds(1));
test = imageNumber + 1;
imageNumber++;
string testFile = test + ".jpg";
if (await appFolder.TryGetItemAsync(testFile) != null)
{
test = 99999;
}
else
{
test = 1;
}
}
while (test == 99999);
}
Live tile doesn't work after upgrading the project from WP7 to WP8. Does anyone know the reason?
I've done an custom tile, and I'm saving it as a picture in IsolatedStorage.
The code for Tile in Scheduled Agent:
.
.
.
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
FlipTileData data = new FlipTileData()
{
SmallBackgroundImage = new Uri("isostore:" + mediumTile, UriKind.RelativeOrAbsolute),
BackgroundImage = new Uri("isostore:" + mediumTile, UriKind.RelativeOrAbsolute),
WideBackgroundImage = new Uri("isostore:" + wideTile, UriKind.RelativeOrAbsolute)
};
tile.Update(data);
}
NotifyComplete();
In order to use an image in your IsolatedStorage, you need to use the /Shared/ShellContent path. Here is your code with the fix:
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
FlipTileData data = new FlipTileData()
{
SmallBackgroundImage = new Uri("isostore:/Shared/ShellContent/" + mediumTile, UriKind.RelativeOrAbsolute),
BackgroundImage = new Uri("isostore:/Shared/ShellContent/" + mediumTile, UriKind.RelativeOrAbsolute),
WideBackgroundImage = new Uri("isostore:/Shared/ShellContent/" + wideTile, UriKind.RelativeOrAbsolute)
};
tile.Update(data);
}
NotifyComplete();
I am trying to create a tile using FlipTileData in Windows Phone 8. I use this code:
const string mainPage = "/MainPage.xaml";
...
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
This throws an InvalidOperationException at the ShellTile.Create method. There are no other tiles with the same Navigation URI. What am I doing wrong here?
This code works fine using the StandardTileData class, excluding the SmallBackgroundImage and WideBackgroundImage properties.
If it matters, the full code is:
const string mainPage = "/MainPage.xaml";
...
private void createbutton_Click(object sender, RoutedEventArgs e)
{
string tileId = new Random().Next().ToString();
Uri mp = new Uri(mainPage + "?" + "tileid=" + tileId, UriKind.Relative);
WriteableBitmap wbmp = new WriteableBitmap(tileGrid, null);
string isourl = "/Shared/ShellContent/" + tileId + ".jpg";
IsolatedStorageFileStream isfs = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(isourl);
wbmp.SaveJpeg(isfs, 173, 173, 0, 100);
isfs.Close();
FlipTileData tileData = new FlipTileData();
tileData.Title = tileTitle;
tileData.BackgroundImage = new Uri("isostore:" + isourl);
tileData.SmallBackgroundImage = new Uri("isostore:" + isourl);
tileData.WideBackgroundImage = new Uri("isostore:" + isourl);
ShellTile.Create(mp, tileData);
}
If using the new tile templates you need to use the overload of ShellTile.Create() that includes a third parameter.
This should do the trick:
ShellTile.Create(mp, tileData, true);
Are you calling this code inside the Closing handler?
In Windows Phone 8, creating a Tile by using the Create(Uri, ShellTileData) method inside the Closing handler will throw an InvalidOperationException.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206947(v=vs.105).aspx
edit: i guess not, since you said it worked with StandardTileData...
I'm new to do C# Windows Phone programming.
In a nutshell, I am currently building an app that will:
Load image A
Load image B
and then Load image C
then use these 3 images to do some post processing.
My Image B and Image C are build as Content within the project.
Image A is chosen from Gallery or taken via camera, or we can simply assume that Image A is load from Isolated Storage.
I am experiencing a problem which I believe caused by asynchronous image loading.
Here's my code:
...
// I intend to load the 3 pictures by calling the method: LoadImage(int id) and LoadCImage();
else if (ListBox.SelectedIndex == 0)
{
Debug.WriteLine("Selected 0");
PhotoProcessor pp = new PhotoProcessor();
WriteableBitmap imageA = new WriteableBitmap(AImage);
WriteableBitmap imageB = LoadImage(0);
WriteableBitmap imageC = LoadCImage();
WriteableBitmap mix = pp.Mix(pp.CalcAverageColour(0), imageA, imageB, imageC);
resultPic.Source = mix;
}
...
And:
private WriteableBitmap LoadImage(int id)
{
//String uriString = "/Assets/img0.jpg";
//BitmapImage img = new BitmapImage(new Uri(uriString, UriKind.Relative));
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.None;
//img.SetSource(Application.GetResourceStream(new Uri("/Assets/facetemplate0.jpg", UriKind.Relative)).Stream);
img.UriSource = new Uri("/Assets/img" + id + ".jpg", UriKind.Relative);
//img.UriSource = new Uri(uriString, UriKind.Relative);
return new WriteableBitmap(img);
}
private WriteableBitmap LoadCImage()
{
//BitmapImage img = new BitmapImage(new Uri("/Assets/imgC.jpg", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.CreateOptions = BitmapCreateOptions.None;
//img.SetSource(Application.GetResourceStream(new Uri("/Assets/imgC.jpg", UriKind.Relative)).Stream);
bmp.UriSource = new Uri("/Assets/imgC.jpg", UriKind.Relative);
return new WriteableBitmap(bmp);
}
Now my question is:
When I'm trying to run this code, it will throw a Null Reference Exception, which is because of the function mix can't load Image A B and C (loading this images are asynchronously).
I wonder if there's a way to let me sequentially load these images then let me to pass them to the mix function?
What I've tried:
By checking this great blog post, I'm able to know that there do have some way to load the image synchronously, but as you can see throughout my code, I tried to use SetSource(stream) like the blogpost, but unfortunately I got the same Null Reference Exception.
I've also thought about the EventHandler method, however I don't think its a good idea in this case. If I implement EventHandler, would it be something like(pseudo code):
imageA_Opened()
{
LoadImageB += imageB_Opened();
}
imageB_Opened()
{
LoadImageC += imageC_Opened();
}
imageC_Opened()
{
PhotoProcessor pp = new PhotoProcessor();
pp.Mix(averageColour, A, B, C);
}
Am I right?
Servy is correct in saying you shouldn't block the UI with synchronous calls.
With that being said, I had a similar requirement in a WP7 app. I used "Async CTP" to add the ability to write synchronous like functions that wait until it's done before making the next call. I had API calls that required data from earlier calls to function correctly.
I believe this was included in .NET 4.5 and works on WP8.
http://msdn.microsoft.com/en-ca/library/vstudio/hh191443.aspx
Here is what I wrote to pull data for my app (Notice the "async" and "await" keywords):
public async Task<bool> GetDefaultData()
{
try
{
_cancellation = new CancellationTokenSource();
UpdateProgress(DateTime.Now + ": Download Started.\n");
List<string> data = await App._apiConnection.DoWorkAsync(_cancellation.Token, ApiInfo.GetBaseDataUriList());
App._apiConnection.Done(data);
UpdateProgress(DateTime.Now + ": Countries: " + App._context.Countries.Count() + "\n");
UpdateProgress(DateTime.Now + ": Regions: " + App._context.Regions.Count() + "\n");
UpdateProgress(DateTime.Now + ": Income Levels: " + App._context.IncomeLevels.Count() + "\n");
UpdateProgress(DateTime.Now + ": Indicators: " + App._context.Indicators.Count() + "\n");
data = await App._apiConnection.DoWorkAsync(_cancellation.Token, ApiInfo.GetCountryUriList("CA"));
App._apiConnection.Done(data);
UpdateProgress(DateTime.Now + ": CA Population: " + App._context.PopulationDatas.Count(c => c.Country.Iso2Code == "CA") + "\n");
data = await App._apiConnection.DoWorkAsync(_cancellation.Token, ApiInfo.GetCountryUriList("US"));
App._apiConnection.Done(data);
UpdateProgress(DateTime.Now + ": US Population: " + App._context.PopulationDatas.Count(c => c.Country.Iso2Code == "US") + "\n");
data = await App._apiConnection.DoWorkAsync(_cancellation.Token, ApiInfo.GetCountryUriList("CN"));
App._apiConnection.Done(data);
UpdateProgress(DateTime.Now + ": CN Population: " + App._context.PopulationDatas.Count(c => c.Country.Iso2Code == "CN") + "\n");
return true;
}
catch (OperationCanceledException)
{
MessageBox.Show("Operation Cancelled");
return false;
}
catch (Exception ex)
{
MessageBox.Show("getDefaultData Exception: " + ex.Message);
return false;
}
}
You're not supposed to be able to download an image sequentially. It would certainly be easier to develop, yes, but it wouldn't be nearly as effective because you would be blocking the processor for an extended period of time, thus freezing your application.
I've also thought about the EventHandler method, however I don't think its a good idea in this case. If I implement EventHandler, would it be something like (pseudo code):
Yep, it would follow that general pattern as you have described it. That's the appropriate way to address this problem.