I have a Windows phone application which gets a list of photos URLs from a SQL database depending what it uploaded.
The issue i have is users can add their own photos to that list but it does not refresh the list on the page so i added a refresh to re run the code but it still does not run.
Well the code runs but does not update the list box.
//get/clean these strings
int parkID = 0;
string parkName = string.Empty;
public photos()
{
InitializeComponent();
BuildLocalizedApplicationBar();
}
private void ThemeParkPhotos_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
//No errors have been passed now need to take this file and parse it
//Its in XML format
XDocument xdox = XDocument.Parse(e.Result);
//need a list for them to be put in to
List<Photos> themeparkPhoto = new List<Photos>();
themeparkPhoto.Clear();
XNamespace ns = "http://schemas.datacontract.org/2004/07/WCFServiceWebRole1";
//Now need to get every element and add it to the list
foreach (XElement item in xdox.Descendants(ns + "Photos"))
{
Photos content = new Photos();
content.ID = Convert.ToInt32(item.Element(ns + "ID").Value);
content.PhotoURL = Convert.ToString(item.Element(ns + "PhotoURL").Value);
//content.ID = Convert.ToInt32(item.Element(ns + "id").Value);
//content.ThemeParkName = item.Element(ns + "name").Value.ToString();
themeparkPhoto.Add(content);
}
ThemeParkPhoto.ItemsSource = null;
ThemeParkPhoto.ItemsSource = themeparkPhoto.ToList();
//Delete all the stuff
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
//There an Error
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//This is to get the data that was passed from the home screen to which song to use!
base.OnNavigatedTo(e);
if ((NavigationContext.QueryString["pID"] == string.Empty) || (NavigationContext.QueryString["pName"] == string.Empty))
{
//if not show message box.
MessageBox.Show("Empty Vaules have been sent, Please got back and try again");
}
else
{
parkID = Convert.ToInt32(NavigationContext.QueryString["pID"]);
parkName = NavigationContext.QueryString["pName"].ToString();
PageName.Text = parkName;
GetThemeParkPhotos();
}
}
public void GetThemeParkPhotos()
{
WebClient ThemeParkPhotos = new WebClient();
ThemeParkPhotos.DownloadStringCompleted += ThemeParkPhotos_DownloadStringCompleted;
ThemeParkPhotos.DownloadStringAsync(new Uri("HIDDEDURL/viewphotos?format=xml&themeparkid=" + parkID));
//MessageBox.Show("Test if this works"+parkID);
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.Opacity = 1.0;
ApplicationBar.IsVisible = true;
ApplicationBar.IsMenuEnabled = true;
ApplicationBarIconButton AddButton = new ApplicationBarIconButton();
AddButton.IconUri = new Uri("/Images/add.png", UriKind.Relative);
AddButton.Text = "Add Photo";
ApplicationBar.Buttons.Add(AddButton);
AddButton.Click +=AddButton_Click;
//Dont add refresh button as it does not work at this time :(
ApplicationBarIconButton RefreshButton = new ApplicationBarIconButton();
RefreshButton.IconUri = new Uri("/Images/refresh.png", UriKind.Relative);
RefreshButton.Text = "Refresh";
ApplicationBar.Buttons.Add(RefreshButton);
RefreshButton.Click += RefreshButton_Click;
}
private void RefreshButton_Click(object sender, EventArgs e)
{
GetThemeParkPhotos();
}
private void AddButton_Click(object sender, EventArgs e)
{
//need to send them to add a photo page with details.
NavigationService.Navigate(new Uri("/TakePhoto.xaml?pID=" + parkID + "&pName=" + parkName, UriKind.Relative));
}
Here the Code for the ListBox
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="559" HorizontalAlignment="Left" Margin="6,20,0,0" x:Name="ThemeParkPhoto" VerticalAlignment="Top" Width="444" FontSize="30" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="ID" Text="{Binding ID}"></TextBlock>
<Image x:Name="PhotoURL" Source="{Binding PhotoURL}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I have removed the URL to save the API, That code does run and fill it but why does it not refresh the List Box correctly?
Many Thanks
Thank to being sent here : C# WebClient disable cache
Turns out that Windows phone web client caches the file meaning it never download it again until the app is refreshed. By using a random number generator and adding it to the then of the URL it will always download the file allowing for a refresh.
Related
I'm working on a UWP Desktop application for video editing and I need to include the subtitles feature. I've did what other questions recommend, but the TimedMetadataTracks list is still empty. Any help is most welcome.
XAML
<MediaPlayerElement x:Name="mediaPlayerElement"
AutoPlay="False"
Margin="5"
Width="640" Height="480"
HorizontalAlignment="Center"
AreTransportControlsEnabled="True" />
Code Behind
private void nviRestore_Tapped(object sender, TappedRoutedEventArgs e)
{
// Create the media source and supplement with external timed text sources
var source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/teste.mp4"));
var ttsEnUri = new Uri("ms-appx:///Assets/en.srt");
var ttsEn = TimedTextSource.CreateFromUri(ttsEnUri);
ttsMap[ttsEn] = ttsEnUri;
ttsEn.Resolved += Tts_Resolved;
source.ExternalTimedTextSources.Add(ttsEn);
// Create the playback item from the source
var playbackItem = new MediaPlaybackItem(source);
playbackItem.TimedMetadataTracksChanged += MediaPlaybackItem_TimedMetadataTracksChanged;
// Set the source to start playback of the item
this.mediaPlayerElement.SetPlaybackSource(playbackItem);
}
private void Tts_Resolved(TimedTextSource sender, TimedTextSourceResolveResultEventArgs args)
{
var ttsUri = ttsMap[sender];
// Handle errors
if (args.Error != null)
{
var ignoreAwaitWarning = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//rootPage.NotifyUser("Error resolving track " + ttsUri + " due to error " + args.Error.ErrorCode, NotifyType.ErrorMessage);
});
return;
}
// Update label manually since the external SRT does not contain it
var ttsUriString = ttsUri.AbsoluteUri;
if (ttsUriString.Contains("_en"))
args.Tracks[0].Label = "English";
}
private async void MediaPlaybackItem_TimedMetadataTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
{
// Present the first track
sender.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
}
I use SearchBar to search from listView and I have other controls
but when page load just SearchBar appear and other controls disappear
like this image
and when search then select from listView the disappeared controls appears
like this image
my xaml code :
<StackLayout>
<SearchBar x:Name="search_trade"
TextChanged="search_trade_TextChanged"
/>
<ListView x:Name="list" ItemSelected="list_ItemSelected" >
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" ></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Editor x:Name="edit_trade"
FontSize="14"/>
</StackLayout>
my c# code :
private void search_trade_TextChanged(object sender, TextChangedEventArgs e)
{
if (search_trade.Text.Trim()==string.Empty)
{
list.IsVisible = false;
}
list.IsVisible = true;
if (string.IsNullOrEmpty(e.NewTextValue))
{
list.ItemsSource = tempdata;
}
else
{
list.ItemsSource = tempdata.Where(x => x.Name.ToLower().StartsWith(e.NewTextValue));
}
}
private void list_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Contacts)e.SelectedItem;
edit_trade.Text = item.Name.ToString();
search_trade.Text = "";
list.IsVisible = false;
edit_trade.IsReadOnly = true;
}
code c# that I initially set the ItemsSource :
public Anti_biotic()
{
InitializeComponent();
active();
years_months();
frame_view.IsVisible = false;
trade();
}
private void trade()
{
tempdata = new List<Contacts>
{
new Contacts() { Name = "Amoclawin228.5mg/5mlsusp60ml"},
new Contacts() { Name = "Amoclawin 457mg / 5ml susp 60 ml"},
new Contacts() { Name = "Amoflux 250 mg susp 100 ml"},
};
}
how can I solve this issue?
you are not assigning the ListView's ItemsSource when the page loads. If the ListView doesn't have any data then it won't display anything
public Anti_biotic()
{
InitializeComponent();
active();
years_months();
frame_view.IsVisible = false;
// this method creates tempdata but doesn't do anything with it
trade();
// add this
list.ItemsSource = tempdata;
}
everyone
I am looking for a idea that helps me to solve my problem. I am trying to create a wpf programm which i could login on a webpage with given username and password in WPF, after that i could also get a successed message.
I have tried with following code:
Xaml file:
<StackPanel Orientation="Horizontal" Background="Black">
<TextBox x:Name="username" Width="200" Margin="2,2,10,2" Text="username"/>
<TextBox x:Name="password" Width="200" Margin="2,2,10,2" Text="password"/>
<Button Width="200" Content="Go!" Margin="2" Click="Button_Click" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="1" >
<WebBrowser x:Name="wb1" Height="500" />
<TextBlock x:Name="state" Text="Connection" ></TextBlock>
</StackPanel>
Code Behinde:
...
public MainWindow()
{
InitializeComponent();
wb1.LoadCompleted += new LoadCompletedEventHandler(bws_LoadCompleted);
wb1.Navigated += new NavigatedEventHandler(bws_Navigated);
}
void bws_Navigated(object sender, NavigationEventArgs e)
{
HideScriptErrors(wb1, true);
}
void bws_LoadCompleted(object sender, NavigationEventArgs e)
{
switch (e.Uri.AbsolutePath)
{
case "/":
DoExample1();
break;
case "/login":
DoExample1();
break;
}
}
private void DoExample1()
{
TryFillInBing(username.Text, password.Text);
}
void TryFillInBing(string name, string passwd)
{
Thread.Sleep(500);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if (!LoginInput(0, "username", "password", name, passwd) && Tries < 6)
{
Tries++;
TryFillInBing(name, passwd);
}
else
{
IHTMLFormElement form = GetForm(0);
form.submit();
}
}));
}
private bool UpdateTextInput(int formId, string name, string text)
{
bool successful = false;
IHTMLFormElement form = GetForm(formId);
if (form != null)
{
var element = form.item(name: name);
if (element != null)
{
var textinput = element as HTMLInputElement;
textinput.value = text;
successful = true;
}
}
return successful;
}
private bool LoginInput(int formId, string name, string passwd, string text, string pw)
{
bool successful = false;
IHTMLFormElement form = GetForm(formId);
if (form != null)
{
var element = form.item(name);
var pass = form.item(passwd);
if (element != null && pass != null)
{
var textinput = element as HTMLInputElement;
textinput.value = text;
var passinput = pass as HTMLInputElement;
passinput.value = pw;
successful = true;
}
}
return successful;
}
...
...
...
private void Button_Click(object sender, RoutedEventArgs e)
{
string conquerclubLogin = "https://www.conquerclub.com";
string googleWeb = "http://www.google.de";
wb1.Navigate(conquerclubLogin);
}
But it showed me the same login page and i did not receive any message for successfull login...Has anyone an idea for me?
Cheers, Carvin
I have a situation with my app whereby the ProgressBar displays correctly when OnNavigatedTo is executed. Then during the process of searching for and collating the data resuested, the ProgressBar hangs/freezes. Finally, when all data has been collected and displayed correctly in the list, the ProgressBar collapses correctly.
My XAML looks like this:
<ProgressBar
x:Name="progressbar"
IsIndeterminate="True"
Minimum="0"
Maximum="100"
Value="0"
Width="400"
Height="30"
Foreground="#FF117B0F"
/>
My C# looks like this:
List<GameLive> gameLive;
public MainPage()
{
InitializeComponent();
gameLive = new List<GameLive>();
ProgressBar progressbar = new ProgressBar();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string htmlPageLive = "";
bool isError = false;
HttpClient client = new HttpClient();
try
{
htmlPageLive = await client.GetStringAsync("webpage");
}
catch (Exception)
{
isError = true;
}
if (isError)
{
MessageBox.Show("Unable to retrieve data");
return;
}
HtmlDocument htmlDocumentLive = new HtmlDocument();
htmlDocumentLive.LoadHtml(htmlPageLive);
foreach (var div in htmlDocumentLive.DocumentNode.SelectNodes("..nav.."))
{
bool isErrorTwo = false;
GameLive newGame = new GameLive();
try
{
newGame.Title = removed;
newGame.Summary = removed;
gameLive.Add(newGame);
}
catch (Exception)
{
isErrorTwo = true;
}
if (isErrorTwo)
{
NavigationService.Navigate(new Uri("/Temp.xaml", UriKind.Relative));
return;
}
}
lstGameLive.ItemsSource = gameLive;
progressbar.Visibility = Visibility.Collapsed;
progressbar.IsIndeterminate = false;
}
I've tried multiple solutions but have run out of options. Can somebody please point me in the right direction here?
Thank you.
It's a problem related to the async methods as they freeze the UI (as I think) till the execution finishes.
You might want to look at this and also this
For a much more cleaner code, try binding the progress bar visibility like this one and this
I have this longListSelector:
<phone:LongListSelector
x:Name="ListaMensajesTablon"
ItemsSource="{Binding Mensajes}"
ItemTemplate="{StaticResource MensajesTablonDataTemplate}"
SelectionChanged="MensajeTablonSelected"/>
With this ItemTemplate:
<DataTemplate x:Key="MensajesTablonDataTemplate">
<Grid>
<Button MaxHeight="85" MaxWidth="95" MinHeight="85" MinWidth="95" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Click="Button_Click" BorderBrush="Transparent">
<Button.Content>
<Image x:Name="imagenFav" MaxHeight="75" MaxWidth="75" MinHeight="75" MinWidth="75"
Source="{Binding userFav, Converter={StaticResource BoolToHeart}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Button.Content>
</Button>
</Grid>
</DataTemplate>
This code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
botonFavPulsado = true;
botonAmor = (Button)sender;
}
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
}
}
I want to do is that when you press a button that is inside an element of LongListSelector change the picture . The first time I press the button enters in the function Button_Click and then enters in the function MensajeTablonSelected function and change the image (good). The problem is the second time I press the same button is entering in the function Button_Click function and does not enter in the function MensajeTablonSelected
Resume : ToggleButton in LongItemSelector working the first time but not the second one
Problem solved:
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if (((LongListSelector)sender).SelectedItem != null)
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
//Unselect ITEM
((LongListSelector)sender).SelectedItem = null;
}
}
This solution have a problem, the function MensajeTablonSelected is called again.