Getting value from a control inside DataTemplate windows phone 7 - windows-phone-7

Iam working on dataTemplate in windows phone 7. I had customised Listbox with data template. now i need to get the values from the customised listbox. Please check the code is below.
<phone:PhoneApplicationPage.Resources>
<Style x:Key="Image_List" TargetType="ListBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Grid>
<Rectangle Fill="#FF030403" RadiusY="10" RadiusX="10" Stroke="#1BA1E2" StrokeThickness="2"/>
<ScrollViewer x:Name="ScrollViewer">
<ItemsPresenter Height="Auto"/>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:PhoneApplicationPage.Resources>
<ListBox BorderBrush="#1BA1E2" Name="Image_Listbox" Margin="5,53,6,6" Style="{StaticResource Image_List}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border CornerRadius="5" BorderBrush="#1BA1E2" BorderThickness="1" Margin="3,1,0,0" Height="69" Width="445">
<StackPanel Margin="0,0,0,0" Background="Transparent" Orientation="Horizontal" Height="69" Width="400">
<CheckBox Name="Images_Check" Margin="0,0,0,0" Content="" Height="67" HorizontalAlignment="Left"/>
<TextBlock TextAlignment="Left" FlowDirection="LeftToRight" Width="Auto" FontSize="22" Text="{Binding UBindData}" Height="40" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Iam getting the UI_Template correctly.the user will check the required Items in the checkbox provided. now i need to get the checked items in my code. can anybody help me out of this? How to get the checked Items and Itemvalue by the user.
Thanks in advance.

I had got solution after a day war.Here it goes.I got solution from nokia developer site. you can get whether checkbox inside datatemplate is checked and its corresponding Textblock value.
//Variables to store the count of checked Checkboxes and their data
public string option_selected = "";
public int check_count = 0;
//SearchElement populates above variables for checkboxes in specified "targeted_control"
public void SearchElement(DependencyObject targeted_control)
{
var count = VisualTreeHelper.GetChildrenCount(targeted_control); // targeted_control is the listbox
if (count > 0)
{
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(targeted_control, i);
if (child is CheckBox) // specific/child control
{
CheckBox targeted_element = (CheckBox)child;
if (targeted_element.IsChecked == true)
{
if (targeted_element.Tag!= null)
{
// get the value associated with the "checked" checkbox
option_selected = targeted_element.Tag.ToString();
}
// count the number of "Checked" checkboxes
//check_count = check_count + 1;
return;
}
}
else
{
SearchElement(child);
}
}
}
else
{
return;
}
}

Related

Parsing an XML generated by REST for WP7

I'm trying to develop a simple WP7 app that queries a REST feed which produces a XML file. Depending on the query, the feed can generate many different XML files, but I am having problems with the most basic one.
The XML I am trying to display in a ListBox looks like;
<subsonic-response status="ok" version="1.1.1">
</subsonic-response>
or
<subsonic-response status="ok" version="1.1.1">
<license valid="true" email="foo#bar.com" key="ABC123DEF" date="2009-09-03T14:46:43"/>
</subsonic-response>
I've tried following several examples from MSDN and other source but I can't seem to wrap my head around it. The URL that I'm using works because it displays the correct information when entered into a browser, but for some reason isn't displayed in the ListBox.
Here is the code I am currently using;
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
namespace RESTTest
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
string requestString =
"http://WEBSITE/rest/{0}.view?u=USERNAME&p=PASSWORD&v=1.8.0&c=RestTest";
string UriNoAppId =
"http://WEBSITE/rest/{0}.view?u=USERNAME&p=PASSWORD&v=1.8.0&c=RestTest";
public MainPage()
{
InitializeComponent();
List<string> searchTopics = new List<string>() { "ping", "getLicense" };
comboBox1.DataContext = searchTopics;
comboBox1.SelectedIndex = 0;
// Create the WebClient and associate a handler with the OpenReadCompleted event.
wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
}
// Call the topic service at the Bing search site.
WebClient wc;
private void CallToWebService()
{
// Call the OpenReadAsyc to make a get request, passing the url with the selected search string.
wc.OpenReadAsync(new Uri(String.Format(requestString, comboBox1.SelectedItem.ToString())));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
XElement resultXml;
// You should always check to see if an error occurred. In this case, the application
// simply returns.
if (e.Error != null)
{
return;
}
else
{
XNamespace web = "http://subsonic.org/restapi";
try
{
resultXml = XElement.Load(e.Result);
// Search for the WebResult node and create a SearchResults object for each one.
var searchResults =
from result in resultXml.Descendants(web + "WebResult")
select new SearchResult
{
// Get the Title, Description and Url values.
Title = result.Element(web + "version").Value,
Url = result.Element(web + "status").Value
};
// Set the data context for the listbox to the results.
listBox1.DataContext = searchResults;
textBox1.DataContext = searchResults;
}
catch (System.Xml.XmlException ex)
{
textBlock2.Text = ex.Message;
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
CallToWebService();
}
// Update the textblock as the combo box selection changes.
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
uriTextBlock.DataContext = string.Format(UriNoAppId, e.AddedItems[0]);
}
}
// Simple class to hold the search results.
public class SearchResult
{
public string Title { get; set; }
public string Url { get; set; }
}
}
XAML
<phone:PhoneApplicationPage
x:Class="RESTTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="False">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.Resources>
<Style x:Key="ComboBoxItemStyle" TargetType="ComboBoxItem" >
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="LightGray"/>
</Style>
<Style x:Key="ComboBoxStyle" TargetType="ComboBox" >
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="Gray"/>
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="REST CLIENT"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Subsonic"
Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"
Height="99" Width="453" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="12,139,12,0" Grid.RowSpan="2">
<Button Content="Search!" Height="89" HorizontalAlignment="Left"
Margin="264,140,0,0" Name="button1"
VerticalAlignment="Top" Width="189" Click="button1_Click" />
<ComboBox Height="50" Style="{StaticResource ComboBoxStyle}"
HorizontalAlignment="Left" Margin="6,159" Name="comboBox1"
ItemContainerStyle="{StaticResource ComboBoxItemStyle}"
VerticalAlignment="Top" Width="235" ItemsSource="{Binding}"
SelectionChanged="comboBox1_SelectionChanged" />
<TextBlock Height="36" HorizontalAlignment="Left" Margin="12,120"
Name="textBlock2" Text="Search Topic:" VerticalAlignment="Top" width="121" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,1,0,0"
Name="textBlock3"
Text="URI:" VerticalAlignment="Top" />
<TextBlock Height="86" HorizontalAlignment="Left" Margin="6,28"
Name="uriTextBlock" TextWrapping="Wrap" Text="{Binding}"
VerticalAlignment="Top" Width="447" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,242,0,0"
Name="textBlock5"
Text="Results:" VerticalAlignment="Top" />
<ListBox Height="169" HorizontalAlignment="Left" Margin="6,271,0,0" Name="listBox1"
VerticalAlignment="Top" Width="444" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{StaticResource PhoneForegroundBrush}" Width="418"
BorderThickness="2" Margin="2">
<StackPanel>
<TextBlock Text="{Binding Path=Title}" TextWrapping="Wrap" />
<TextBlock Text="{Binding Path=Url}" TextWrapping="Wrap"/>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox Height="209" HorizontalAlignment="Left" Margin="6,446,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="444" IsEnabled="True" IsReadOnly="True" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
The code is currently designed so you can choose to display either one of the example XML files, but nothing is displayed in the Listbox at all.
Any advice would be appreciated. Thank you.
See if the following helps:
string fakeXML = "<subsonic-response status='ok' version='1.1.1'>" +
"<license valid='true' email='foo#bar.com' " +
" key='ABC123DEF' date='2009-09-03T14:46:43'/>" +
"</subsonic-response>";
XDocument doc = XDocument.Parse(fakeXML);
var searchResults = from xe in doc.Elements("subsonic-response")
select new SearchResult
{
Title = xe.Attribute("version").Value,
Url = xe.Attribute("status").Value
};
listBox1.DataContext = searchResults;
textBox1.DataContext = searchResults;

Getting custom data from ListPicker

I have a ListPicker in my app which is defined like that:
<DataTemplate x:Name="PickerItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding code}" Margin="12 0 0 0" Visibility="Collapsed"/>
<TextBlock Text="{Binding name}" Margin="12 0 0 0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="PickerFullModeItemTemplate">
<StackPanel Orientation="Horizontal" Margin="16 21 0 20">
<TextBlock Text="{Binding name}" Margin="16 0 0 0"
FontSize="43" FontFamily="{StaticResource PhoneFontFamilyLight}"/>
</StackPanel>
</DataTemplate>
<toolkit:ListPicker x:Name="_1stLanguageListPicker"
ItemTemplate="{StaticResource PickerItemTemplate}"
FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}"
Header="1st Specie Name Language"
FullModeHeader="1st Specie Name Language"
CacheMode="BitmapCache"/>
As you can see I show to user only the full name, hidding the code. But as a programmer I would like to use code name.
How to get to this name?
I have tried like that
if (_1stLanguageListPicker.SelectedIndex == 0)
{
firstlang = "GB"
}
But not working (some bool to int problem, normal = doesn't work also) and this is a bad way for many items list as you have to put many many IF statements.
What I understand is, Your problem is to get the data of the code TextBlock in the code behind.
First give some name to your TextBlock
<TextBlock x:Name="codeTextBlock" Text="{Binding code}" />
And then use the following code to access the 'code'
if (listPicker.SelectedIndex > -1)
{
var item = listPicker.ItemContainerGenerator.ContainerFromIndex(listPicker.SelectedIndex);
SearchVisualTree(item);
}
Here, SearchVisualTree() is:
private void SearchVisualTree(DependencyObject targetElement)
{
var count = VisualTreeHelper.GetChildrenCount(targetElement);
if (count == 0)
return;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(targetElement, i);
if (child is TextBlock)
{
TextBlock targetItem = (TextBlock)child;
if (targetItem.Name == "codeTextBlock")
{
var code = targetItem.Text;
return;
}
}
else
{
SearchVisualTree(child);
}
}
}
One possible problem here is(which you faced), we cannot access the DataTemplate before ListPicker is Loaded. In other workds, before DataTemplate is generated for the ListPicker.
So the placement of the above code is very important.
Hope this helps

How to show list of items when click on button in wp7?

i placed one button in a page .when click on that need to show 1 to 30 numbers in combobox as a popup in that page only.please tell me how to acheive this?
Edit:
I have edited the answer with design,add an image as a local content in the project
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Button" Height="82" HorizontalAlignment="Left" Margin="44,59,0,0" Name="button1" VerticalAlignment="Top" Width="376" Click="button1_Click" />
<ListBox ItemsSource="{Binding item}" Width="376" Name="lst" Margin="56,128,48,76" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" DataContext="{Binding}" BorderBrush="Black">
<StackPanel Width="376" Orientation="Vertical" Height="Auto">
<Image Margin="200,20,-75,5" Height="50" Width="50" Source="{Binding img}"></Image>
<TextBlock Margin="-200,-15,90,3" Height="50" Width="50" Name="text" Text="{Binding text}" Foreground="Black"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
lst.visibility = visibility.collapsed;
private void button1_Click(object sender, RoutedEventArgs e)
{
lst.visibility = visibility.visible;
List<Itemss> data = new List<Itemss>();
for (int i = 0; i < 30; i++)
{
Itemss item = new Itemss();
item.text = i.ToString();
item.img = "/images.jpg";
data.Add(item);
}
lst.ItemsSource = data;
}
public class Itemss
{
public string text { get; set; }
public string img { get; set; }
}
}
YOu can make use of the ListPicker for WP7 instead of a ComboBox for WP7.
And to show the ListPicker in a popup, Place the ListPicker in a MessagePrompt.

How to select the textbox in data template

while programming for windows phone 7, I created a listbox and using DataTemplate which contains a textblock and a textbox. The textbox is hided by default.
The XAML:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Width="460" Height="60" Background="{StaticResource PhoneAccentBrush}">
<TextBlock Text="{Binding data}" FontSize="30" Margin="10,10,10,0"/>
<TextBox Height="60" Width="460" Visibility="Collapsed"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The effect I wanna accomplish is : Tap textblock to hide textblock while show textbox.
CODE BEHIND:
private void TextBlock_Tap(object sender, GestureEventArgs e)
{
TextBlock.Visibilty = Visibility.Collapsed;
TextBox.Visibilty = Visibility.Visible;
}
However, obviously the selector isn't correct. I tried to add Name for textbox and textblock, but Name seems does not work in Data Template. Is there anyone who can tell me how can i select the textblock and textbox in a Data Template please? Many Thanks!!!
Try this :
<ListBox Name="lst" >
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Width="460" Height="60" Background="{StaticResource PhoneAccentBrush}" Tap="Canvas_Tap">
<TextBlock Text="{Binding}" FontSize="30" Margin="10,10,10,10"/>
<TextBox Height="60" Width="460" Visibility="Collapsed" Text="text"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And in code behind:
private void Canvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var m = (sender as Canvas).Children;
foreach (UIElement x in m)
{
if ((x as TextBlock) != null)
(x as TextBlock).Visibility = Visibility.Collapsed;
if ((x as TextBox) != null)
(x as TextBox).Visibility = Visibility.Visible;
}
}
Setting the Name on the template does work, but you can't access it directly!
Instead, try it like this:
<ListBox x:Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Width="460" Height="60" Background="{StaticResource PhoneAccentBrush}">
<TextBlock x:Name="MyTextBlock" Text="{Binding data}" FontSize="30" Margin="10,10,10,0" Tap="MyTextBlock_Tap" />
<TextBox x:Name="MyTextBox" Height="60" Width="460" Visibility="Collapsed"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And the code:
private void MyTextBlock_Tap(object sender, GestureEventArgs e)
{
var elem = (FrameworkElement)sender;
var myTextBlock = (TextBlock)elem.FindName("MyTextBlock");
var myTextBox = (TextBox)elem.FindName("MyTextBox");
myTextBlock.Visibility = Visibility.Collapsed;
myTextBox.Visibility = Visibility.Visible;
}

Disable pivot flick for WP7

seeing this blog post : http://mine.tuxfamily.org/?p=111, I'm trying to disable the pivot flick when flicking on a control inside the pivot.
I've tryed the proposed solution with IsHitTestVisible, but it seems that the application locks when setting it to false.
To reproduce the problem, create a wp7 basic application. Use this xaml :
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid x:Name="ContentPanel" Margin="12,0,12,0">
<controls:Pivot Name="pivotCtrl" Grid.Row="1">
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value1}"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Height="38" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" Text="{Binding Value1}" />
<TextBlock Grid.Row="1" Height="38" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200" Text="{Binding Value2}" />
<Canvas Grid.Row="2" Width="400" Height="300" Background="Yellow" MouseLeftButtonUp="Canvas_MouseLeftButtonUp" MouseLeftButtonDown="Canvas_MouseLeftButtonDown" />
</Grid>
</DataTemplate>
</controls:Pivot.ItemTemplate>
</controls:Pivot>
</Grid>
</Grid>
with this code behing :
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
List<Element> elements = new List<Element>();
for (int i = 0 ; i < 10 ; i++)
elements.Add(new Element { Value1 = "Value - " + i, Value2 = "Something - " + i});
pivotCtrl.ItemsSource = elements;
}
private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("On");
pivotCtrl.IsHitTestVisible = true;
}
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("Off");
pivotCtrl.IsHitTestVisible = false;
}
}
public class Element
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
In debug mode, I can see the "Off" value, but never the "On" one.
Maybe there's another solution for this.
Thanks in advance for your help.
This solution was posted this week. Does it work better for you?
Preventing the Pivot or Panorama controls from scrolling

Resources