Drag and drop reorder list box was closed - windows-phone-8

In test.xaml
<rlb:ReorderListBox
x:Name="reorderListBox"
Grid.Row="2"
Margin="12,0,12,12"
IsReorderEnabled="True"
ItemsSource="{Binding}" >
<rlb:ReorderListBox.ItemTemplate>
<DataTemplate>
<TextBlock
Margin="12,4,12,4"
FontSize="36"
Text="{Binding Name}" />
</DataTemplate>
</rlb:ReorderListBox.ItemTemplate>
</rlb:ReorderListBox>
int Test.xaml.cs
public void loadSource()
{
try
{
var xElem = XElement.Load("Data/SourcePage.xml");
var SourceNews =
from elem in xElem.Descendants("SourceNews")
select new ProNewsApp.Object.ObjectSource
{
Name = elem.Attribute("PageName").Value
};
reorderListBox.DataContext = SourceNews.ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm follow here http://reorderlistbox.codeplex.com/ and my problem is when i'm drag and drop and my app was closed ?Why it's closed when I drag item ?How do i fix it

You need to use an ObservableCollection as the source of ReorderListBox. As the ReorderListbox changes indexes when items are reordered in the Model. So, try using:
System.Collections.ObjectModel.ObservableCollection<YourPublicClass> _observableList;
_observableList = new System.Collections.ObjectModel.ObservableCollection<YourPublicClass>(SourceNews.ToList());
reorderListBox.DataContext = _observableList;
And after rearranging items you can see that they are also changed in "_observableList".

Related

Strange primefaces horizontal bar behaviour

I need your help to understand a very strange primefaces horizontal bar behaviour.
What I'd like to do is to draw a horizontal bar with primefaces.
Here are all my datas I get from my postgresql db table:
For the following explanations please refer to this horbarchart image:
If I get only first five banks from my db everything's ok! (1)
If I try to get and show all the banks disaster happens :( Only eight banks are shown and values are shifted. (2)
Finally, if I try to get and show the last four banks only two are shown with wrong values. (3)
Obviously, I checked with my debugger's IDE if every chart serie was populated correctly and everything is build in a very right way.
This is my (hibernate) class that gets datas from db:
public class ChartRequestTypeJPA {
static final transient Logger LOGGER = LogManager.getLogger(ChartRequestTypeJPA.class.getName());
static final transient ResourceBundle BUNDLE = FacesContext.getCurrentInstance().getApplication().getResourceBundle(FacesContext.getCurrentInstance(), "txt");
public List<ChartRequestType> getAll(TimeInterval step) throws Exception {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session
.createCriteria(ChartRequestType.class)
.add(Restrictions.eq("pk.step", step.getDescr()));
List<ChartRequestType> result = criteria.list();
return result;
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error getting chart request type" + e.getMessage());
throw new DMLException(BUNDLE.getString("message.noDataFound"));
} finally {
if (session != null) {
session.close();
}
}
}
}
This is my class that sets the bar chart model:
#ManagedBean
#RequestScoped
public class Chart11RequestTypeView {
private HorizontalBarChartModel chartRequestTypeModel;
private void createHorizontalBarModel() {
chartRequestTypeModel = new HorizontalBarChartModel();
ChartSeries informazioni = new ChartSeries();
ChartSeries anomalia = new ChartSeries();
ChartSeries rio = new ChartSeries();
// Valori percentuali della singola banca sul totale letto da oracle
informazioni.setLabel(TXT.getString("uilabel.chart11.informazioni"));
anomalia.setLabel(TXT.getString("uilabel.chart11.anomalia"));
rio.setLabel(TXT.getString("uilabel.chart11.rio"));
int size = chartRequestType.size();
for (int i = 0; i < size; i++) {
String tipologia = chartRequestType.get(i).getPk().getTipologia();
String bankName = chartRequestType.get(i).getPk().getName();
int tickNumb = chartRequestType.get(i).getTicketnumber();
switch(tipologia){
case "Anomalia":{
anomalia.set(bankName, (int) tickNumb);
break;
}
case "Informazioni":{
informazioni.set(bankName, (int) tickNumb);
break;
}
case "Richiesta Operativa":{
rio.set(bankName, (int)tickNumb);
break;
}
}
if(chartRequestType.get(i).getPk().getTipologia().equals("Informazioni")){
informazioni.set(chartRequestType.get(i).getPk().getName(), chartRequestType.get(i).getTicketnumber());
}
if(chartRequestType.get(i).getPk().getTipologia().equals("Anomalia")){
anomalia.set(chartRequestType.get(i).getPk().getName(), chartRequestType.get(i).getTicketnumber());
}
if(chartRequestType.get(i).getPk().getTipologia().equals("Richiesta Operativa")){
rio.set(chartRequestType.get(i).getPk().getName(), chartRequestType.get(i).getTicketnumber());
}
}
chartRequestTypeModel.setSeriesColors("999999,666666,333333");
chartRequestTypeModel.setTitle(TXT.getString("uilabel.chart11.title"));
chartRequestTypeModel.addSeries(anomalia);
chartRequestTypeModel.addSeries(informazioni);
chartRequestTypeModel.addSeries(rio);
Axis xAxis = chartRequestTypeModel.getAxis(AxisType.X);
xAxis.setLabel(TXT.getString("uilabel.chart11.number"));
xAxis.setMin(0);
xAxis.setTickAngle(40);
xAxis.setTickFormat("%d");
chartRequestTypeModel.setExtender("chartRequestTypeExtender");
// horizontalBarModel.setShowPointLabels(true); qui non serve, sta nell'extender
}
}
Finally, this is my xhtml:
<p:panel style="text-align: center; width:100%; border: 0px;">
<p:panelGrid id="pchart11" columns="1" style="text-align: center; margin-bottom:10px; width: 100%; height:600px;">
<p:row>
<p:chart type="bar" model="#{chart11RequestTypeView.chartRequestTypeModel}" style="height:600px;" />
</p:row>
</p:panelGrid>
</p:panel>
<script language="javascript" type="text/javascript">
function chartRequestTypeExtender() {
this.cfg.sortData = true; // forse superfluo
this.cfg.legend = {
show: true,
location: 'e',
placement: 'insideGrid'
};
this.cfg.grid = {
background: 'transparent',
gridLineColor: '#D0D0FF',
drawBorder: false
};
this.cfg.seriesDefaults = {
renderer:$.jqplot.BarRenderer,
// Show point labels to the right ('e'ast) of each bar.
// edgeTolerance of -15 allows labels flow outside the grid
// up to 15 pixels. If they flow out more than that, they
// will be hidden.
pointLabels: { show: true, location: 'e', edgeTolerance: -15 },
// Rotate the bar shadow as if bar is lit from top right.
shadowAngle: 135,
// Here's where we tell the chart it is oriented horizontally.
rendererOptions: {
barDirection: 'horizontal'
}
};
this.cfg.highlighter = {
show: true,
tooltipAxes: 'x', // da usare anche in altri chart, evita l'ambiguita dei tootips tipo 3,7 inteso come 3.7 anzichè valore 7 per il punto 3
useAxesFormatters: false,
tooltipFormatString: "%i"};
}
</script>
</html>
Can anyone help me?
Thank you so much for listening me
Solved!
Primefaces barcharts need to have the same number of values for every ChartSeries to format them correctly. I populate my three series with different number of values for every bank; this was the problem!
So, be careful to populate every ChartSeries with the same number of values.
Enojoy! :)

Windows Phone 8 Can't Update listbox item in XML file after using hardware back button?

Hi All i have a list box and i am saving list box selected item in XML file thats working fine but the problem is that when i will close my app and reopen and add more value to list box my previous value is removed form the xml file and listbox also how i can save my current added value and previous value in xml file i am using following code :
and iam using following code
<Grid x:Name="ContentPanel" Grid.Row="2" Margin="15,10,15,0">
<ListBox Name="list_location" Tap="list_location_Tap" Foreground="Black">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="item_name" Text="{Binding description, Mode=OneWay}" Padding="5,15,5,15" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Name="list_locationAdd" Background="Red" Foreground="Black" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="item_name" Text="{Binding description, Mode=OneWay}" Padding="5,15,5,15" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
and my back end code is follow:
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = ISF.OpenFile(filename, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
serializer.Serialize(xmlWriter, data);
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
try
{
if (list_locationAdd != null)
{
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream str = ISF.OpenFile(filename, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
ObservableCollection<Prediction> data = (ObservableCollection<Prediction>)serializer.Deserialize(str);
if (list_locationAdd != null)
{
this.list_locationAdd.ItemsSource = data;
list_locationAdd.Visibility = Visibility.Visible;
}
}
}
}
}
catch (Exception ex)
{
}
}
Change in your code as per below :
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = ISF.OpenFile(filename, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
serializer.Serialize(xmlWriter, data);
}
}
Update in your current code :
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
if (isoStore.FileExists(filename))
{
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
ObservableCollection<Prediction> data = (ObservableCollection<Prediction>)serializer.Deserialize(isoStream);
this.list_locationAdd.ItemsSource = data;
}
}
catch(Exception ex)
{ }
}
else
{
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore))
{
XmlSerializer Serialize = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter writer = XmlWriter.Create(isoStream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
Serialize.Serialize(writer, data);
}
}
}
catch (Exception ex)
{ }
}
Hope this is helpful to you.

Search Bar - Suggestoin of Places (Bing Map) Windows Phone App 8.1

I want to add Search to Bing Map Control in my Windows Phone app. I did not find any references on the internet
Scenario
1. When the user enters the name of the place. The List Box will open to show the suggested places
2. The User will select the a single option and the coordinates of the location or pushpin will be displayed to that particular area.
Help me Out Please
It's fairly easy to accomplish. You need an AutoSuggestBox:
<AutoSuggestBox TextChanged="AutoSuggestBox_TextChanged" SuggestionChosen="AutoSuggestBox_SuggestionChosen">
<AutoSuggestBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Address.PostCode}" />
<TextBlock Text="," />
<TextBlock Text="{Binding Path=Address.Town}" />
</StackPanel>
</DataTemplate>
</AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>
And when the text changes you issue a query. Since a server request takes some time, make sure that you choose a reasonable response interval. So DO NOT issue a query if the input has just changed for one char.
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
if (sender.Text.Length > 3)
{
// Build a hint point
Geopoint hintPoint = [..]; // Up to you, should reflect the current location
await this.Progressbar.ShowAsync();
sender.ItemsSource = await getMapSuggestionsAsync(sender.Text, hintPoint);
await this.Progressbar.HideAsync();
}
else {
sender.ItemsSource = new List<MapLocation> { };
}
}
}
All you need now is a method that issues your query:
public static async Task<List<MapLocation>> getMapSuggestionsAsync(String query, Geopoint hintPoint)
{
List<MapLocation> locations = new List<MapLocation>();
// Find a corresponding location
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(query, hintPoint, 2);
// If the query provides results, try to get the respective city name and
// a zip code or deny first.
if (result.Status != MapLocationFinderStatus.Success)
return locations;
foreach (var location in result.Locations)
{
MapLocation ml = await resolveLocationForGeopoint(location.Point);
if (ml != null)
locations.Add(ml);
}
return locations;
}
public static async Task<MapLocation> resolveLocationForGeopoint(Geopoint geopoint)
{
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(geopoint);
if (result.Status == MapLocationFinderStatus.Success)
{
if (result.Locations.Count != 0)
// Check if the result is really valid
if (result.Locations[0].Address.Town != "")
return result.Locations[0];
}
return null;
}
The rest is simple: If the user chooses a suggestion you get the coordinates out of the MapLocation and show a pushpin on your map.
This is some code I wrote to get a Zip code and the city name. But you can really change it to search for anything else..

Autosuggestbox not displaying results WP8.1 Universal App

Results template in autosuggestbox are not showing and I don't know why. I'm using MVVM Light in the app. Let's go with the code :)
In the page:
<AutoSuggestBox x:Name="txtBusqueda" x:Uid="txtBusqueda"
ItemsSource="{Binding Lugares}"
Grid.Row="1" Margin="24 24 24 12"
MaxSuggestionListHeight="4" AutoMaximizeSuggestionArea="True"
TextMemberPath="Nombre"
>
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="TextChanged">
<core:InvokeCommandAction Command="{Binding ChangeTextCommand}" CommandParameter="{Binding Text, ElementName=txtBusqueda}" />
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
<AutoSuggestBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Nombre}" TextWrapping="Wrap" />
</DataTemplate>
</AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>
In the VM:
private List<LugarInfo> lugares;
public List<LugarInfo> Lugares
{
get { return this.lugares; }
set
{
if (this.lugares == value) return;
this.lugares = value;
RaisePropertyChanged(() => Lugares);
}
}
public RelayCommand<string> ChangeTextCommand { get; set; }
this.ChangeTextCommand = new RelayCommand<string>(async (s) =>
{
var result = await Api.GetInfoLugares(texto);
List<LugarInfo> lugares = new List<LugarInfo>();
foreach (var lugar in result)
{
lugares.Add(new LugarInfo()
{
Id = int.Parse(lugar.Id),
Tipo = lugar.Tipo,
Nombre = lugar.Nombre
});
}
this.Lugares = lugares;
});
So, as you can see, not too much trouble.
The results are returned and assigned to the property:
The problem is results are not displayed in control as you can see in the image.
Help will be appreciated.
your Lugares property will never raise RaisePropertyChanged because in your code you are adding your objects in lugares and than assigning it to This.Lugares which in setter is same so it will not raise the property change and and UI is not updated. change your code to as follows.
var myLugares = new List<LugarInfo>();
foreach (var lugar in result)
{
myLugares.Add(new LugarInfo()
{
Id = int.Parse(lugar.Id),
Tipo = lugar.Tipo,
Nombre = lugar.Nombre
});
}
this.Lugares = myLugares;

WinRT RenderTargetBitmap seems not to obey transforms

I'm trying to render some UIElements to a RenderTargetBitmap.
I have an Image, that is moved around the base Element using a TranslateTransform.
When I use RenderTargetTransform.RenderAsync, the Image is rendered without the transform.
I tried using Margin instead, but RenderTargetBitMap does not obey that either.
Can I make it actually use that transform?
Here's the code, the XAML part:
<Page
x:Class="W8RT_POC.RTBTransform"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:W8RT_POC"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Grid x:Name="RenderGrid" Grid.Row="0"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<Image x:Name="RenderImage"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Source="Assets/Move_Normal.png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" >
<Image.RenderTransform>
<CompositeTransform TranslateX="100" TranslateY="100"/>
</Image.RenderTransform>
</Image>
</Grid>
<Button x:Name="GoButton" Content="GO" Grid.Row="1"
HorizontalAlignment="Left" Click="GoButton_Click" />
</Grid>
</Page>
... and the code behind:
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Imaging;
namespace W8RT_POC
{
public sealed partial class RTBTransform : Page
{
public RTBTransform()
{
this.InitializeComponent();
}
private async void GoButton_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
// Fixed on Filip Skakun's comment. await rtb.RenderAsync(RenderGrid, (int)this.RenderGrid.Width, (int)this.RenderGrid.Height);
await rtb.RenderAsync(RenderGrid, (int)this.RenderGrid.ActualWidth, (int)this.RenderGrid.ActualHeight);
await SaveRenderTargetBitmap(rtb);
}
private async Task SaveRenderTargetBitmap(RenderTargetBitmap RtbToSave)
{
var picker = new Windows.Storage.Pickers.FileSavePicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeChoices.Add("GIF file", new string[] { ".gif" });
picker.DefaultFileExtension = ".gif";
picker.SuggestedFileName = "Illustration " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
Windows.Storage.StorageFile file = await picker.PickSaveFileAsync();
if (file != null)
{
Guid encoderId = Windows.Graphics.Imaging.BitmapEncoder.GifEncoderId;
var bitmapPropertySet = new Windows.Graphics.Imaging.BitmapPropertySet();
using (var writeStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(encoderId, writeStream);
byte[] pixels = await GetPixels(RtbToSave);
encoder.SetPixelData(
Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied,
(uint)RtbToSave.PixelWidth,
(uint)RtbToSave.PixelHeight,
96,
96,
pixels);
await encoder.FlushAsync();
using (var outputStream = writeStream.GetOutputStreamAt(0))
{
await outputStream.FlushAsync();
}
} // using(writeStream)
} // if (file != null)
}
private static async Task<byte[]> GetPixels(RenderTargetBitmap bitmap)
{
// Get pixels from the RenderTargetBitmap. See http://social.technet.microsoft.com/wiki/contents/articles/20648.using-the-rendertargetbitmap-in-windows-store-apps-with-xaml-and-c.aspx
// Bytes are in BGRA8 format.
Windows.Storage.Streams.IBuffer pixelBuffer = await bitmap.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
return pixels;
}
}
}
This is what I see on screen (see tha black part left and top):
... and this goes to the saved file (that is created by RenderTargetBitMap.RenderAsync):