I am trying to display data from my SQL Server Compact 3.5. On my OnNavigateTo function, I have stated the codes but I am not sure why it is not able to load it. I am using Pivot App, Is it possible to use that to display my data? If yes, what have I done wrong. In the header=today is where I am displaying my data. Thanks.
Below are my codes
MainPage.xaml
<!--Pivot Control-->
<phone:Pivot Title="DAILY ROUTINE">
<!--Pivot item one-->
<phone:PivotItem Header="activity">
<!--Double line list with text wrapping-->
<phone:LongListSelector x:Name="MLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="LongListSelector_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PivotItem>
<!--Pivot item two-->
<phone:PivotItem Header="today">
<!--Double line list with text wrapping-->
<phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="LongListSelector_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding Id}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PivotItem>
</phone:Pivot>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyPhoneApp1.Resources;
namespace MyPhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
/*
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
* */
using (ToDoListContext c = new ToDoListContext(ToDoListContext.ConnectionString))
{
c.CreateIfNotExists();
c.LogDebug = true;
MainLongListSelector.ItemsSource = c.ToDoLists.ToList();
}
}
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var si = MLongListSelector.SelectedItem as MyPhoneApp1.ViewModels.ItemViewModel;
if (MLongListSelector.SelectedItem == null)
return;
if (si.LineOne.Equals("+ To Do List"))
NavigationService.Navigate(new Uri("/todolistPage.xaml", UriKind.Relative));
else if (si.LineOne.Equals("+ Reminder"))
NavigationService.Navigate(new Uri("/reminderPage.xaml", UriKind.Relative));
// Reset selected item to null (no selection)
MLongListSelector.SelectedItem = null;
}
}
}
I have debugged it and below is the SQL Statements
SELECT [t0].[Id], [t0].[Title]
FROM [ToDoLists] AS [t0]
I wouldn't suggest you directly set the ItemsSource property as you've already established a Binding in the XAML:
<phone:LongListSelector x:Name="MLongListSelector"
ItemsSource="{Binding Items}" >
Since the Binding Path is set to Items, changing the data of the list stored in Items will cause the UI to update automatically.
// get the list ...
var list = c.ToDoLists.ToList();
Debug.Assert(list != null);
// clear any existing items, which will in turn remove all items from the UI
App.ViewModel.Items.Clear();
// for each item in the list, add it to the existing bound Items list
foreach(var item in list) {
// you may need to transform the data here
// The item must be the right type ...
App.ViewModel.Items.Add(item);
}
As it looks like you're using the WP8 template, the ToDoLists property needs to return an enumerable list of ItemViewModels or the call to Add will fail. You could create new instances of an ItemViewModel if the types don't match (for example):
var itemViewModel = new ItemViewModel() {
LineOne = item.Text,
LineTwo = item.Description
};
App.ViewModel.Items.Add(itemViewModel);
The above code assumes then that a todo list item might look like this:
public class TodoItem {
public string Text { get; set; }
public string Description { get; set; }
}
I think this might be the problem you are binding the MainLongListSelector twice
in Xaml
ItemsSource="{Binding Items}"
and in c#
MainLongListSelector.ItemsSource = c.ToDoLists.ToList();
Looks like you need to remove the xaml binding
Related
I want add Text to ListView element when i press button:
private void button_Click(object sender, RoutedEventArgs e)
{
listView.Items.Add(textBox.Text);
}
It works but i got:
Element1
Element2
Element3
But i want to see something like:
[]Element1
[]Element2
Where [ ] is checkbox :)
My xaml:
<ListView x:Name="listView" HorizontalAlignment="Left" Height="406" Margin="10,224,0,0" VerticalAlignment="Top" Width="340" />
I don't see option CheckBoxes True/False in my xaml Properties
XAML
Modify the listView item template to add your custom layout.
Add a data binding to the set the text
<ListView x:Name="listView" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="340">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<CheckBox/>
<Label Content="{Binding Text}"/>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code Behind
declare this class somewhere
public class Row
{
private string text;
public Row (string text)
{
this.text = text;
}
public string Text
{
get { return text; }
set { text = value; }
}
}
Add this code to the constructor of the code associated with the xaml
ObservableCollection<Row> list = new ObservableCollection<Row>();
listView.ItemsSource = list;
How to add items/text to the listView
list.Add(new Row("Hello"));
list.Add(new Row("World"));
Hope this helps!
In CS File "SelectedItem" is not working what is the alternative to "SelectedItem" for AutoSuggestBox in WP8.1
In XAML File:
<AutoSuggestBox x:Name="tblkpersonname" Width="380" Margin="0,-7,0,0" ItemsSource="{Binding}" TextChanged="tblkpersonname_TextChanged">
<AutoSuggestBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
Tag="{Binding PersonID}"/>
</DataTemplate>
</AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>
In Cs File:
private void tblkpersonname_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
try
{
if (tblkpersonname.SelectedItem != null)
{
tblkdes.Text = ((values)tblkpersonname.SelectedItem).Description;
persononlineimg.Source = new BitmapImage(new Uri(((values)tblkpersonname.SelectedItem).FlickrPersonImageUrl, UriKind.RelativeOrAbsolute));
}
}
catch (Exception ex)
{
Exceptions.SaveOrSendExceptions("Exception in tblkpersonname_SelectionChanged_1 Method In AddCast.cs file.", ex);
}
}
There's no "SelectedItem" in the AutoSuggestBox provided with Windows Phone 8.1 and neither there's one in the developer tools for Windows 10.
The AutoSuggestBox works like a regular TextBox, the only plus here's the possibility to have a panel/popup that show ups for giving suggestions based on the ItemsSource you passed.
Actually it only works if the ItemsSource is a collection of string, since the DisplayMemberPath doesn't work, at least for me.
So the only way to retrieve the "SelectedItem" you should use the Text property.
I know it's not actually the same, but the AutoSuggestBox it's not a ComboBox.
Xaml
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
<AutoSuggestBox
Text="{Binding EnteredAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding AddressAutoComplete}"
ItemTemplate="{StaticResource Autocomplete}"
TextMemberPath="name">
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SuggestionChosen">
<core:InvokeCommandAction Command="{Binding TextSearchChangedCommand}" CommandParameter="{Binding this}">
</core:InvokeCommandAction>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
ViewModel (Prism)
TextSearchChangedCommand = new DelegateCommand<Object>((Object) =>
{
method(Object);
});
public void method(Object adr)
{
AutoSuggestBoxSuggestionChosenEventArgs a = (AutoSuggestBoxSuggestionChosenEventArgs)adr;
Address selected = (Address)a.SelectedItem;
}
I spent a whole day to realize it:-)
I am a new developer on Windows Phone 8.1, I am try to reach a specific ListView item from the ListView collection and be able to color it or color the TextBock inside of it, But I can't reach the item or reach any of items inside of ListView, Please take a look for my below code :
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteRT db1 = new SQLiteRT();
var db_connection = await db1.Connection("MyDB.sqlite");
List<MyTBL> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;");
db_connection.Close();
LV_Options.ItemsSource = t_list;
}
// my List View called LV_Options
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView lv1 = sender as ListView;
if (lv1 == null)
return;
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
tb.FontSize = 17; // here I got debug error (it not worked !!!!!!!)
var item = LV_Options.Items.ElementAt(3); // this seems not work also !!!!
item.BackColor = Color.LightSteelBlue;
}
As you can see above, I tried to reach a specific item by LV_Options.Items.ElementAt(3) but it doesn't work! I also tried to reach the TextBlock from the selected List view item, but also not worked !
(Updated)
XAML code :
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Name="TB_Rslt" Text="Here result of your answer" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="page title" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<!--TODO: Content should be placed within the following grid-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,10,19,15">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="TB_Question" Text="Choose Answer " Margin="0,0,25,0" HorizontalAlignment="Right" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" />
<TextBlock Name="TB_EnWord" Text="" Margin="90,0,15,0" HorizontalAlignment="Left" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" TextAlignment="Right" />
<StackPanel Grid.Row="1" Margin="5,22,0,0">
<ListView Name="LV_Options" SelectionChanged="LV_Options_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding AMean1}" TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<Button Name="Btn_Answer" Content="Ansewr" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Click="Btn_Answer_Click"/>
My application is a quiz application that offer 4 choices/options as answers for each question, and when user select a true answer, I want to highlight the true answer(true choice) by make its background to green, and if the user selected wrong answer/option I want to make the background of that answer (a specific List View item) with red.
Any help please ?
You're not going to be able to access an element inside a data template like that. Instead, leverage the binding to a view model to set the color and other view-related properties. First, create a wrapper view model for your data class:
public class MyTBLViewModel : INotifyPropertyChanged
{
public MyTBL Entity
{
get { return _entity; }
}
private readonly MyTBL _entity;
public Brush Highlight
{
get { return _brush; }
set
{
_brush = value;
RaisePropertyChanged("Highlight");
}
}
private Brush _highlight;
public double ItemFontSize
{
get { return _itemFontSize; }
set
{
_itemFontSize = value;
RaisePropertyChanged("ItemFontSize");
}
}
private Brush _itemFontSize;
public MyTBLViewModel(MyTBL entity)
{
_entity = entity;
_highlight = new SolidColorBrush(Colors.Transparent);
_itemFontSize = 12;
}
public event PropertyChangedEventArgs PropertyChanged;
protected void RaisePropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propName));
}
}
Use this as your ItemsSource:
List<MyTBLViewModel> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;")
.AsEnumerable().Select(entity => new MyTBLViewModel(entity)).ToList();
Now in your view, bind the view elements to "Highlight" and "ItemFontSize", and to any other properties you like:
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6" Background="{Binding Highlight}">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding Entity.AMean1}" TextWrapping="Wrap"
FontSize="{Binding ItemFontSize}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Finally, you can get the data item from the SelectionChangedEventArgs -- use it to update your view-related properties:
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Color.LightSteelBlue);
item.ItemFontSize = 17;
}
foreach (var item in e.RemovedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Colors.Transparent);
item.ItemFontSize = 12;
}
}
var item = LV_Options.Items.ElementAt(3);
This line is incorrect. It will not return you a TextBlock. I don't know what a .BackColor is, and it should not compile. The Items property in a ListView will return you a list of ListViewItems. If you want to access the inside element from a ListViewItem, you'll need to access the ContentTemplateRoot property.
Do not use var ever. It lets you assume that you know the type, whereas if you explicitly typed the declaration you would realize you're doing it wrong.
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
What is a MyTBL type? FindName is only available to framework DependencyObjects so I'm assuming it's a user control? You have to provide a lot more code to show us what you're doing and what you're setting the ListView's ItemsSource and ItemTemplate with and what these errors are and how you have 2 breaking debug errors at once and what the error messages are.
Comprehending runtime error messages is a huge part of being a good developer.
Can someone see what I need to change here? I am displaying an observablecollection of AddressTypeClass items. The object items show up in the listbox instead of the data. I can see the data in the objects in debug mode.
THE XAML.CS FILE:
DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = new ObservableCollection<AddressTypeClass>(new MyTableDataContext().AddressTypes.AsEnumerable()
.Select(lt => new AddressTypeClass
{
AddressTypeID = lt.AddressTypeID,
AddressType = lt.AddressType,
})
.ToList());
this.listBox1.ItemsSource = theOC;
THE XAML FILE:
<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806" ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
</ListBox>
You need to add an ItemTemplate to your ListBox, e.g.
<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806" ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=AddressType}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can impove your code by using my ObservableComputations library. In your code you manualy update theOC every time MyTableDataContext.AddressTypes dbSet (I assume you are using EntityFramework) changes (new item or remove) or properties (AddressType.AddressTypeID, AddressType.AddressType) changes. Using AddressType you can automate that process:
DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = MyTableDataContext.AddressTypes.Local
.Selecting(lt => new AddressTypeClass
{
AddressTypeID = lt.AddressTypeID,
AddressType = lt.AddressType,
});
this.listBox1.ItemsSource = theOC;
theOC is ObservableCollection and reflects all the changes in the MyTableDataContext.AddressTypes.Local collection and properties mentioned in the code above. Ensure that all properties mentioned in the code above notify of changes through the INotifyProperytChanged interface.
I've got a ListBox in a WP7 App where I want to do something with an item when the user hold it. The event work's great. My hold method gets called, but I can't detect which element in the list was hold.
ListBox.SelectedItem is always -1 and a code from another post on stackoverflow doens't work:
FrameWorkelement element = (FrameworkElement) e.OriginalSource;
ItemViewModel item = (ItemViewModel) element.DataContext;
I get an InvalidCastException when running it in the second line.
The following code should work.
private void StackPanel_Hold(object sender, GestureEventArgs e)
{
ItemViewModel itemViewModel = (sender as StackPanel).DataContext as ItemViewModel;
string t = itemViewModel.LineOne;
}
Note: before using the DataContext of the sender object, make sure you cast the sender object to the correct class. In this example I use a StackPanel in my DataTemplate:
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Height="78" Hold="StackPanel_Hold">
<TextBlock Text="{Binding LineOne}" />
<TextBlock Text="{Binding LineTwo}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>