Multimarkers in a bing Map - c#

I am having a problem in putting a marker for every location in my bing map, this is my code:
private async void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
await
// Need to get back onto UI thread before updating location information
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(
async () =>
{
UriString4 = "my URL";
var http = new HttpClient();
http.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await http.GetStringAsync(UriString4);
var rootObject = JsonConvert.DeserializeObject<NvBarberry.Models.RootObject>(response);
Location[] location = new Location[int.Parse(rootObject.total)];
for (int i = 0; i < int.Parse(rootObject.total); i++)
{
//Get the current location
location[i] = new Location(rootObject.locals[i].local_latit,rootObject.locals[i].local_longi);
//Update the position of the GPS pushpin
MapLayer.SetPosition(GpsIcon, location[i]);
//Set the radius of the Accuracy Circle
GpsIcon.SetRadius(args.Position.Coordinate.Accuracy);
//Make GPS pushpin visible
GpsIcon.Visibility = Windows.UI.Xaml.Visibility.Visible;
//Update the map view to the current GPS location
MyMap.SetView(location[i], 17);
}
}));}
This is the JSON data from where I want to get the local_longi and
local_latit of every Location:
{
success : 1,
total : 2,
locals : [{
id_local : "59",
local_longi : "20",
local_latit : "25894"
}, {
id_local : "60",
local_longi : "10.33699",
local_latit : "25.997745"
}
]
}
The problem is that I get only one marker on the map, which is the last Location from Longitude, Lattitude (according to tha JSON data I get on Map only the location with this values:
local_longi: "10.33699",
local_latit: "25.997745"
And this is what I get when debugging:
I get all results in "location" variable, why I get only one marker in the Map
this is the tutorial that I have followed:
https://blogs.bing.com/maps/2012/11/05/getting-started-with-bing-maps-windows-store-apps-native/
Update:
this is my xaml code for the Map:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<m:Map Name="MyMap" Credentials="1m8dxWklva2lte3kYjkn~........" ZoomLevel="13" />
<CheckBox Content="GPS" Click="GPS_Checked"/>
</Grid>

Hey try to bind a OberservableCollection of Pushpin(Class from me).
<Maps:MapItemsControl ItemsSource="{x:Bind ViewModel.Pushpins}">
<Maps:MapItemsControl.ItemTemplate>
<DataTemplate x:DataType="model:Pushpin">
<StackPanel Maps:MapControl.Location="{x:Bind Location, Converter={StaticResource PointConverter}}"
Maps:MapControl.NormalizedAnchorPoint="{x:Bind Path='', Converter={StaticResource DefaultAnchorPointConverter}}">
<TextBlock Text="{x:Bind Title}"
Foreground="Black" />
<Image Source="{x:Bind Path='', Converter={StaticResource PushpinConverter}}" />
</StackPanel>
</DataTemplate>
</Maps:MapItemsControl.ItemTemplate>
</Maps:MapItemsControl>

Related

MapControl Template10

SOLVED
I solved this problem with the fact that I have to add a MapItemsControl.ItemTemplate. Without this it does not render anything more than the name of the control.
So just add this code:
<Maps:MapItemsControl x:Name="mainMapItems" ItemsSource="{Binding MapItems}">
<Maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="Transparent">
<TextBlock Maps:MapControl.Location="{Binding Location}" Text="{Binding Title}" Maps:MapControl.NormalizedAnchorPoint="0.5,0.5" FontSize="20" Margin="5"/>
</StackPanel>
</DataTemplate>
</Maps:MapItemsControl.ItemTemplate>
</Maps:MapItemsControl>
It's not perfect because this will not give you an icon on the map, but rather just a text. But it can easily be solve with adding Image = "" in the Collection.
I'm trying to use MapControl in a Template10 layout.
The code I use is
MainPage.xaml
<Maps:MapControl x:Name="MapControl1"
ZoomInteractionMode="GestureAndControl"
TiltInteractionMode="GestureAndControl"
MapServiceToken="<ApiCodeHere>"
Loaded="{x:Bind ViewModel.Map_Loaded}"/>
MainPageViewModel.cs
MapControl _Map;
public MapControl Map { get { return _Map; } set { Set(ref _Map, value); RaisePropertyChanged(); } }
public async void Map_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
MapControl newMap = new MapControl();
Geoposition userLocation = await GetUserLocation();
BasicGeoposition GeoPos_UserLocation = new BasicGeoposition() { Latitude = userLocation.Coordinate.Point.Position.Latitude, Longitude = userLocation.Coordinate.Point.Position.Longitude };
BasicGeoposition GeoPos_NorthWest = new BasicGeoposition() { Latitude = userLocation.Coordinate.Point.Position.Latitude + 0.05, Longitude = userLocation.Coordinate.Point.Position.Latitude + 0.1 };
BasicGeoposition GeoPos_SouthEast = new BasicGeoposition() { Latitude = userLocation.Coordinate.Point.Position.Latitude - 0.05, Longitude = userLocation.Coordinate.Point.Position.Latitude - 0.1 };
GeoboundingBox mapBox = new GeoboundingBox(GeoPos_NorthWest, GeoPos_SouthEast);
// Add Point for User
MapIcon Icon_UserLocation = new MapIcon() { Location = new Geopoint(GeoPos_UserLocation) };
newMap.MapElements.Add(Icon_UserLocation);
newMap.Center = new Geopoint(mapBox.Center);
Map = newMap;
await Task.CompletedTask;
}
The Map_Loaded function is fired as exepcted. The thing that I have a trouble with is that if this was a normal project I would set the data directly to MapControl1.Center and MapControl1.MapElements.Add. But since this is a MVVM project this is not how it's done and I'm a bit confused on how to proceed.
I would like to do something like Views.MainPage.MapControl1.Center = new Geopoint(), but that clearly does not work.
Additional Update
As it turns out this was as easy as I thought. It was just a matter of thinking in the right order.
The MapControl has controls for Zooming and Center and such. So for MVVM code this works
Center="{Binding MapCenter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Zoom="{Binding MapZoom,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
I have however had issues with setting up MapItems as described in the document I sources to.
To get items on the map you need to add MapItemsControl and it should work like such...
<Maps:MapItemsControl x:Name="mainMapItems" ItemsSource="{Binding MapItems,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></Maps:MapItemsControl>
But my code in MainPageViewModel.xaml does not work with this. The items does not update.
IList<MapElement> _MapItems;
public IList<MapElement> MapItems { get { return _MapItems; } set { Set(ref _MapItems, value); RaisePropertyChanged(); } }
IList<MapElement> MapItems = new List<MapElement>() {
new MapIcon() {
Location = new Geopoint(GeoPos_UserLocation),
Title = "You Are Here!"
}
};
Sources: Windows 10 SDK Bing Maps Control
Try using
ObservableCollection ObserverableCollection<MapElement> MapItems =
new ObservableCollection<MapElement>();
Since you expecting the item to be "updatable at runtime" or react to changes ObservableCollection behind the scenes implements INPC
I solved this problem with the fact that I have to add a MapItemsControl.ItemTemplate. Without this it does not render anything more than the name of the control.
So just add this code:
<Maps:MapItemsControl x:Name="mainMapItems" ItemsSource="{Binding MapItems}">
<Maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="Transparent">
<TextBlock Maps:MapControl.Location="{Binding Location}" Text="{Binding Title}" Maps:MapControl.NormalizedAnchorPoint="0.5,0.5" FontSize="20" Margin="5"/>
</StackPanel>
</DataTemplate>
</Maps:MapItemsControl.ItemTemplate>
</Maps:MapItemsControl>
It's not perfect because this will not give you an icon on the map, but rather just a text. But it can easily be solve with adding Image = "" in the Collection.

Windows Phone 8.1 with Bing maps returns Access violation

I am trying to bind a collections of points to the Bing map control and everything works great for the first time (when I am opening the view with this map for the first time) but every another attempt end up with this pure message in the output window:
The program 'xxx' has exited with code -1073741819 (0xc0000005) 'Access violation'.
There is no exceptions, nothing only this message. What I have tried so far is this article from MSDN but without success. I have also tried to run the code on the UI thread but it didn't help.
In the ViewModel I am doing this:
Issues.Completed += () =>
{
Locations = new ObservableCollection<MapItemViewModel>();
foreach (var issueLto in Issues.Result)
{
Locations.Add(new MapItemViewModel
{
Name = issueLto.Title,
Location = new MapPointViewModel
{
Longitude = issueLto.Longitude,
Latitude = issueLto.Latitude
}
});
}
MapCenter = Issues.Result.Select(c => new MapCenterViewModel
{
Location = new MapPointViewModel
{
Latitude = c.Latitude,
Longitude = c.Longitude
}
}).FirstOrDefault();
};
And the XAML:
<maps:MapControl
MapServiceToken="{StaticResource BingServiceToken}"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Center="{Binding MapCenter.Location, Converter={StaticResource MapCoordinatesConverter}}">
<maps:MapItemsControl ItemsSource="{Binding Locations}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel maps:MapControl.Location="{Binding Location, Converter={StaticResource MapCoordinatesConverter}}">
<TextBlock Text="{Binding Name}" Foreground="Black"/>
<Image Source="../../Assets/mappin.png" Height="25"/>
</StackPanel>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:MapControl>
It's maybe because you can't bind the center property of the Map Control, there's a workaround using Behavior SDK, please read this article:
http://dreamteam-mobile.com/blog/2012/10/better-bing-maps-sdk-for-metro-apps-winrt-windows8-en/
in MSDN, this is helpful:
https://social.msdn.microsoft.com/Forums/en-US/436fc737-19c8-4832-a1c4-368f88063616/anyway-to-make-a-binding?forum=bingmapswindows8

How to add a UI element above Map Icon to show address in Windows 10?

I am working on MapControl in Windows 10 and I want to display Location Address above map icon. I know how to add a map icon but not aware of adding a UI element above it. I added Map Icon using following code
MapControl map = frameworkElement as MapControl;
map.MapServiceToken= "my service token";
BasicGeoposition councilPosition = new BasicGeoposition()
{
Latitude = Convert.ToDouble(Info.GetType().GetRuntimeProperty("LATITUDE").GetValue(Info, null)),
Longitude = Convert.ToDouble(Info.GetType().GetRuntimeProperty("LONGITUDE").GetValue(Info, null))
};
Geopoint pinPoint = new Geopoint(councilPosition);
MapIcon locationPin = new MapIcon();
locationPin.Image= RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Images/pushpin.png"));
locationPin.Title = councilInfo.COUNCIL_NAME;
locationPin.CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible;
locationPin.Location = councilPoint;
locationPin.NormalizedAnchorPoint = new Point(0.5, 1.0);
locationPin.ZIndex = 0;
map.MapElements.Add(locationPin);
await map.TrySetViewAsync(locationPin.Location, 15D, 0, 0, MapAnimationKind.Bow);
and I want to achieve same as below screenshots
Since programmatic adding MapIcons is hectic for custom template. Here's how I am using map Control inside my app
<maps:MapControl x:Name="MapControl" MapServiceToken="YourToken" >
<maps:MapItemsControl ItemsSource="{Binding YourData, Mode=TwoWay}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Tapped="MapIcon_Tapped" Orientation="Horizontal">
<Image Height="30" VerticalAlignment="Top" maps:MapControl.Location="{Binding Location}" maps:MapControl.NormalizedAnchorPoint="0.5,0.5" Source="ms-appx:///Images/pushpin.png"/>
<Border BorderThickness="1" BorderBrush="LightGray" Visibility="{Binding DetailsVisibility}">
<StackPanel x:Name="MapIcon" Background="White" >
<TextBlock Text="{Binding yourMin}" Foreground="Black" FontWeight="SemiBold" FontSize="16" Margin="5" TextWrapping="WrapWholeWords" />
<TextBlock Text="{Binding YourCar}" Foreground="Gray" FontWeight="SemiBold" FontSize="12" Margin="5" TextWrapping="WrapWholeWords"/>
<Image Source="Your Arrow"/>
</StackPanel>
</Border>
</StackPanel>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:MapControl>
Now here you just need to keep adding data to YourData to add more pushpin.
There are two properties added
1. Location- Is of Geopoint type which will take care of position where pushpin should be placed based on latitude and longitude e.g temp.Location = new Geopoint(new BasicGeoposition { Latitude = double.Parse(temp.Lat), Longitude = double.Parse(temp.Long) });
2. Visibility- This will be used to handle the pushpin detail visibility to be available only on taping it. eg. temp.DetailsVisibility = Windows.UI.Xaml.Visibility.Collapsed;
You will need to add these values to YourData for binding.
I know how to add a map icon but not aware of adding a UI element above it.
If you need to add UIElement above the MapIcon, a possible way is to add UIElement into MapControl’s Children and set to the same coordinate( MapControl.SetLocation).
Here is a simple sample:
BasicGeoposition snPosition = new BasicGeoposition() { Latitude = 47.643, Longitude = -122.131 };
Geopoint snPoint = new Geopoint(snPosition);
Grid MyGrid = new Grid();
MyGrid.Background = new SolidColorBrush(Windows.UI.Colors.Blue);
TextBlock text = new TextBlock();
text.Text = "Hello";
text.Width = 200;
MyGrid.Children.Add(text);
MyMapControl.Center = snPoint;
MyMapControl.ZoomLevel = 14;
// Get the address from a `Geopoint` location.
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(snPoint);
if (result.Status == MapLocationFinderStatus.Success)
{
text.Text = "Street = " + result.Locations[0].Address.Street;
}
MyMapControl.Children.Add(MyGrid);
MapControl.SetLocation(MyGrid, snPoint);
MapControl.SetNormalizedAnchorPoint(MyGrid, new Point(0.5, 0.5));
Screenshot(gif):

Telerik RadJumpList using DataVirtualizationMode.Automatic

I have a problem where im trying to use a Telerik Jump List with DataVirtualizationMode.Automatic, but i can't get it to work. The reason why i want to use this, is because i want my app to only download the data(games) which is in the current view of the Jump List control and not the whole data everytime. For example if i have searched for "Batman", and its returning 50 games, i don't want it to download and load all the games, only those i can see in the Jump List control.
Here is a sample of using DataVirtualizationMode.Automatic from Telerik, but i couldn't get it to work with my app: http://www.telerik.com/help/windows-phone/raddataboundlistbox-features-datavirtualization-automatic.html
Below is my Jump List control which i want to use with data virtualization.
MainPage.xaml:
<phone:PivotItem Header="Browse">
<Grid>
<telerikPrimitives:RadTextBox Name="txtSearch" HorizontalAlignment="Left" VerticalAlignment="Top" Height="80" Width="390"/>
<telerikPrimitives:RadImageButton Name="imgBtnSeachGame" VerticalAlignment="Top" HorizontalAlignment="Right" ButtonShape="Ellipse" BorderThickness="2" Margin="0,8,0,0" Click="imgBtnSeachGame_Click"></telerikPrimitives:RadImageButton>
<Controls:RadJumpList Name="jlGameList" ItemsSource="{Binding}" Tap="jlGameList_Tap" Margin="0,90,0,0" DataVirtualizationMode="Automatic">
<Controls:RadJumpList.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="{StaticResource PhoneAccentBrush}"
Padding="{StaticResource PhoneTouchTargetOverhang}"
Margin="0,0,0,0">
<TextBlock Name="tblGameTitle" Style="{StaticResource PhoneTextGroupHeaderStyle}" ManipulationStarted="tblGameTitle_ManipulationStarted" ManipulationCompleted="tblGameTitle_ManipulationCompleted">
<Run Text="{Binding GameTitle}"></Run>
</TextBlock>
</Border>
<Grid Background="#242424" Grid.Row="1">
<Image Name="imgGameList" Margin="0,0,0,0" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top" Height="96" Width="96">
<Image.Source>
<BitmapImage UriSource="{Binding BoxArtFrontThumb}"
CreateOptions="BackgroundCreation" DecodePixelHeight="96" DecodePixelWidth="96" />
</Image.Source>
</Image>
<TextBlock Margin="110,0,0,0" Text="Platform" FontWeight="Bold" TextWrapping="Wrap" Foreground="YellowGreen" FontSize="{StaticResource PhoneFontSizeNormal}"/>
<TextBlock Name="txtPlatform" Margin="110,20,0,0" Text="{Binding Platform}"></TextBlock>
<TextBlock Text="Release Date" FontWeight="Bold" Margin="110,46,0,0" Foreground="YellowGreen" FontSize="{StaticResource PhoneFontSizeNormal}"/>
<TextBlock Name="txtReleaseDate" Margin="110,66,0,0" Text="{Binding ReleaseDate}"></TextBlock>
<!--</StackPanel>-->
</Grid>
<Grid Grid.Row="2"></Grid>
</Grid>
</DataTemplate>
</Controls:RadJumpList.ItemTemplate>
</Controls:RadJumpList>
</Grid>
</phone:PivotItem>
Below is where i bind my DataContext to my GetGamesListItems ObservableCollection in my GameData class. The imgBtnSearchGame_Click event method is being called when a user have typed for example "Batman" in my textbox txtSearch and tapped the button, it will then send the text to my GetGamesListData method.
MainPage.cs:
GameData gd = new GameData();
public MainPage()
{
InitializeComponent();
jlGameList.DataContext = gd.GetGamesListItems;
}
private void imgBtnSeachGame_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(txtSearch.Text))
{
gd.GetGamesListData(txtSearch.Text, "", "");
}
}
Below is where i download the data in XML for the game name searched for. For example if it is "Batman" it will find and return all games with "Batman". The "BoxArtFrontThumb" Property is where im storing all the images for each game and is using async, because sometimes there can be quite alot of images it has to download and show.
GameData.cs
public void GetGamesListData(string name, string platform, string genre)
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += GetGamesListRequestCompleted;
webClient.DownloadStringAsync(new Uri("http://thegamesdb.net/api/GetGamesList.php?name=" + name));
}
private async void GetGamesListRequestCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
GetGamesListItems.Clear();
var feedXml = XDocument.Parse(e.Result);
var gameDataTasks = feedXml.Root.Descendants("Game").Select(
async x => new GetGamesList
{
ID = (int)x.Element("id"),
GameTitle = (string)x.Element("GameTitle"),
ReleaseDate = (string)x.Element("ReleaseDate") ?? "N/A",
Platform = (string)x.Element("Platform") ?? "N/A",
BoxArtFrontThumb = new Uri(await GetBoxArtFrontThumbAsync((int)x.Element("id")), UriKind.RelativeOrAbsolute),
}).ToList();
var gameData = await Task.WhenAll(gameDataTasks);
foreach (var item in gameData)
{
GetGamesListItems.Add(item);
}
}
}
Below is where its finding and storing the images for the games.
public async Task<string> GetBoxArtFrontThumbAsync(int id)
{
var client = new HttpClient();
var result = await client.GetStringAsync("http://thegamesdb.net/api/GetArt.php?id=" + id);
var feedXml = XDocument.Parse(result);
var gameData = feedXml.Root.Descendants("Images").Select(x => new GetArt
{
BoxArtFrontThumb = new Uri(GetBoxArtFrontThumb(x), UriKind.RelativeOrAbsolute),
}).ToList();
return gameData.Single().BoxArtFrontThumb.ToString();
}
private static string GetBoxArtFrontThumb(XElement gameNode)
{
string data = "http://thegamesdb.net/banners/" + (string)gameNode.Descendants("boxart")
.FirstOrDefault(b => (string)b.Attribute("side") == "front");
if (data == "http://thegamesdb.net/banners/")
{
data = "/NoImage.jpg";
}
return data;
}
I really hope i explained this well enough and hope that there is someone that can help me solve this problem. Thanks.
Although you are using JumpList, the mechanism for Virtualizing the data is the same as the DataBoundListBox. (You can find more information here in the DataBoundListBox docs. There is a good tutorial using an OData service.)
In order for the Automatic mode to work properly, you need to be using Telerik's VirtualizingDataCollection object and initialize it with the proper arguments (count and page size).
I don't see this in the code you have provided above, can you please open a support ticket so that I can investigate further? See my comment above for the link. Let me know the ticket number and I'll provide further assistance.

Pass radio button content between pages

I want to pass radio button content between pages.
XAML Code:
<RadioButton Name="errorCorrectionHLevelRadioButton"
Content="H (~30% correction)"
GroupName="errorCorrectionLevel"
IsChecked="True" BorderBrush="Black" Foreground="Black" Background="Black"
/>
<RadioButton Name="errorCorrectionLLevelRadioButton"
Content="Q (~25% correction)"
GroupName="errorCorrectionLevel" BorderBrush="Black" Foreground="Black" Background="Black"
/>
<RadioButton Name="errorCorrectionMLevelRadioButton"
Content="M (~15% correction)"
GroupName="errorCorrectionLevel" BorderBrush="Black" Foreground="Black" Background="Black"
/>
<RadioButton Name="errorCorrectionQLevelRadioButton"
Content="L (~7% correction)"
GroupName="errorCorrectionLevel" BorderBrush="Black" Foreground="Black" Background="Black"
/>
First page code:
string myECL;
if (errorCorrectionHLevelRadioButton.IsChecked == true)
myECL = ErrorCorrectionLevel.H.ToString();
else if (errorCorrectionQLevelRadioButton.IsChecked == true)
myECL = ErrorCorrectionLevel.Q.ToString();
else if (errorCorrectionMLevelRadioButton.IsChecked == true)
myECL = ErrorCorrectionLevel.M.ToString();
else
myECL = ErrorCorrectionLevel.L.ToString();
NavigationService.Navigate(new Uri("/QRGeneratePage.xaml?text=" + textToEncodeTextBox.Text +"&errorCorrection="+myECL+"&logo="+logoQrCodeImage.Source, UriKind.Relative));
And on the second page I want to use date form radio buton.
For example:
I have a constructor where:
string errorCorrectionLevelChoose = String.Empty;
if (NavigationContext.QueryString.TryGetValue("errorCorrection", out errorCorrectionLevelChoose))
{
ErrorCorrectionLevel ecl = (ZXing.QrCode.Internal.ErrorCorrectionLevel)errorCorrectionLevelChoose;
}
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Renderer = new ZXing.Rendering.WriteableBitmapRenderer()
{
Foreground = colorQRCode
},
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
Height = 300,
Width = 300,
Margin = 1,
ErrorCorrection = ErrorCorrectionLevel.H
}
};
In this line ErrorCorrection = ErrorCorrectionLevel.H I want to use my data from radio button.
So if user choose
<RadioButton Name="errorCorrectionLLevelRadioButton"
Content="Q (~25% correction)"
GroupName="errorCorrectionLevel" BorderBrush="Black" Foreground="Black" Background="Black"
/>
On the second page it will be:
ErrorCorrection = ErrorCorrectionLevel.Q
Do you know how I can do this ?
So a quick and dirty way of passing any type of object, including UIElements is to stick them in the PhoneApplicationService.Current.State dictionary
It is of type Dictionary<String,Object>
For example, if you had a RadioButton you wanted to put in there you could
var myButton = PhoneApplicationService.Current.State.add("MyRadioButton",TheInstanceOfMyRadioButton);
Then, once you navigate to your next page you pull it back out
PhoneApplicationService.Current.State["MyRadioButton"]
All that said, you would be much better off just passing the value of the radio button
For example,
bool isChecked = (bool)MyRadioButton.IsChecked;
PhoneApplicationService.Current.State.add("MyRadioButtonIsChecked",isChecked);
Then to retrieve it
bool isChecked = (bool)PhoneApplicationService.Current.State["MyRadioButtonIsChecked"]
If you want only to pass a variable you can use NavigationService to pass it - for example do it like this:
On the first page, when Navigating (I assume your Q is the variable you want to pass):
string myQ = Q.ToString();
NavigationService.Navigate(new Uri("/secondPage.xaml?Q=" + myQ, UriKind.Relative));
On the second page, in OnNavigatingTo() read that variable:
string myQ;
NavigationContext.QueryString.TryGetValue("myQ", out myQ);
// it's string so you probably need to for example Q = int.Parse(myQ);
If you want to send more complex objects you can do it like here - you can write an extension:
public static class Extensions
{
private static object Data;
public static void Navigate(this NavigationService navigationService,
Uri source, object data)
{
Data = data;
navigationService.Navigate(source);
}
public static object GetNavigationData(this NavigationService service)
{
return Data;
}
}
Usage:
NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.RelativeOrAbsolute), ErrorCorrectionLevel.H);
Then after Navigating you use:
object myQ = NavigationService.GetNavigationData();
ErrorCorrection fromPreviousPage = (ZXing.QrCode.Internal.ErrorCorrectionLevel)myQ;
You can also read some more here.

Categories