Windows Phone 7 Listbox selection data binding - windows-phone-7

I'm using this tutorial as a base for my first app. I'm trying to select a listbox item and view data from said item, but(my Android and iOS brain is having issues with this), how do I view the data binding behind that?
lstContact.ItemsSource = from contact in xmlContact.Descendants("contact")
select new ContactItem
{
ImageSource = contact.Element("Image").Value,
FName = contact.Element("FName").Value,
LName = contact.Element("LName").Value
Extension = contact.Element("Extension").Value,
Email = contact.Element("Email").Value,
ID = contact.Element("ID").Value
};
This is how I'm setting it up my data source, and it's pulling correctly. How would I go about going in and getting the email or extension from said listbox item?

In your example, lstContact.ItemsSource is effectively now a IEnumerable<ContactItem>. Assuming you want a 'selected' item, in your SelectionChanged event:
public void ListBoxContainerSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstContact.SelectedIndex == -1) return;
ContactItem contactItem = (ContactItem)lstContact.SelectedItem;
/*do something */
lstContact.SelectedIndex = -1;
}

Related

Event when Xamarin ListView BindingContext item changes

Is is possible to get an event when an item in the collection bound to a Xamarin Forms listview changes?
For example my object has a Date field which is bound to a label in a ViewCell. I would like an event fired when the Date is changed. Our object implements INotifyPropertyChanged so the listview updates properly.
I can manually subscribe to the OnPropertyChanged event of each item but I'm hoping their is an easier way.
Thanks.
There are triggers in Xamarin.Forms. It seems like an event trigger will do what you need. For example:
<EventTrigger Event="TextChanged">
<local:NumericValidationTriggerAction />
</EventTrigger>
public class NumericValidationTriggerAction : TriggerAction<Entry>
{
protected override void Invoke (Entry entry)
{
double result;
bool isValid = Double.TryParse (entry.Text, out result);
entry.TextColor = isValid ? Color.Default : Color.Red;
}
}
You can find more information about triggers here
See this example for deleting an object when it is selected from a list view.
private MyItemsViewModel _myItemsViewModel;
private void MyItemsListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
MyItem item = (MyItem)e.SelectedItem;
if (item == null)
return;
// remove the item from the ObservableCollection
_myItemsViewModel.Items.Remove(item);
}

Dynamically generated columns in radgrid disappear after postback

Am using radgrid and creating it in aspx but on certain action i add more GridTemplateColumns to the grid.
private void CreateDateColumns(List<DateTime> occurenceList)
{
if (occurenceList != null && occurenceList.Count > 0)
{
int index = 1;
foreach (DateTime occurence in occurenceList)
{
string templateColumnName = occurence.Date.ToShortDateString();
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new MyTemplate(templateColumnName, index);
grdStudentAttendanceList.MasterTableView.Columns.Add(templateColumn);
templateColumn.HeaderText = templateColumnName;
templateColumn.UniqueName = templateColumnName;
index++;
}
}
}
private class MyTemplate : ITemplate
{
protected RadComboBox rcbAttendance;
private string colname;
private int _index;
public MyTemplate(string cName, int index)
{
colname = cName;
_index = index;
}
public void InstantiateIn(System.Web.UI.Control container)
{
rcbAttendance = new RadComboBox();
rcbAttendance.Items.Add(new RadComboBoxItem("---Select---", "-1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Present", "1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Absent", "2"));
rcbAttendance.Items.Add(new RadComboBoxItem("Leave", "3"));
rcbAttendance.ID = "rcbAttendance" + _index;
container.Controls.Add(rcbAttendance);
}
}
All are fine with creation but when i press save button or any combobox make postback the only dynamically generated columns content disappear and the other columns stay.
What i noticed that columns still in place with headertext but only content are disappeared (in my case content are comboboxes)
After enabling viewstate for grid only header text appear.
What should i do to keep columns contents after postback and get their values ?
When creating template columns programmatically, the grid must be generated completely in the code-behind using the Page_Init event. Then, you must create the templates dynamically in the code-behind and assign them to the ItemTemplate and EditItemTemplate properties of the column. To create a template dynamically, you must define a custom class that implements the ITemplate interface. Then you can assign an instance of this class to the ItemTemplate or EditTemplateTemplate property of the GridTemplateColumn object.
Blockquote
Column templates must be added in the Page_Init event handler, so that the template controls can be added to the ViewState.
Blockquote
Source: Telerik
Basicly, you need to create all GridTemplateColumns in the Page_Init. We had the same problem and this approach fixed it.

WP7 delete item from listBox via message box

need some help, when i click the tap_event I get a message box delete or cancel which works and the price is taken off the total but it does'nt update the shopping cart after, it crashes on "ListBoxCart.Items.Remove(curr), thanks in advance!
private void listBoxCart_Tap(object sender, GestureEventArgs e)
{
if (MessageBox.Show("Are you sure!", "Delete", MessageBoxButton.OKCancel)
== MessageBoxResult.OK)
{
foreach (Dvd curr in thisapp.ShoppingCart)
{
if (curr.Equals(listBoxCart.SelectedItem))
{
listBoxCart.Items.Remove(curr);
listBoxCart.SelectedIndex = -1;
total -= Convert.ToDecimal(curr.price);
NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
}
}
txtBoxTotal.Text = total.ToString();
listBoxCart.ItemsSource = thisapp.ShoppingCart;
}
else
{
NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
}
}
I have wrote an artile (sorry in french but you can read the XAML) : http://www.peug.net/2012/05/17/contextmenu-dans-listbox-datatemplate/
and in the code-behind : an example :
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var menuItem = sender as MenuItem;
var fe = VisualTreeHelper.GetParent(menuItem) as FrameworkElement;
Dvd _fig = fe.DataContext as Dvd;
thisapp.ShoppingCart.Remove(_fig);
reloading();
}
When you set the ItemsSource property for the ListBox, it generates a read-only collection and displays them. What you're trying to do is access this read-only collection and modify it but because it's read-only, you can't do that.
Instead you can either have your collection implement the INotifyCollectionChanged interface and raise a collection changed event when the user has deleted the item or use an ObservableCollection instead to store your items. ObservableCollection implements the INotifyCollectionChanged interface for you so you can remove items from the ObservableCollection and the changes will reflect in the Listbox automatically.
ObservableCollection also implements INotifyPropertyChanged so any property updates will also be updated in the ListBox.

SelectedValue of a new item in Combobox

I have been using the Ajax Combo box and I bind it from database, and all works fine. Later I used the selected value to get the results using Linq.
But whenever I add a new item in the same, that is combo box, I get the selected text as the selected value, so in that case it creates an exception.
What can be the better way of getting the selected value of the new item so that I can just by pass the exception.
Should I give it a temporary Id?
How to do that?
Cmbx.DataSource = ScmsFeeBLObj.Mthod();
Cmbx.DataTextField = "Text";
Cmbx.DataValueField = "Id";
Cmbx.DataBind();
protected void Cmbx_SelectedIndexChanged(object sender, EventArgs e)
{
String Id = Cmbx.SelectedValue.ToString();
obj = ScmsFeeBLObj.FillData(Id);
}
Back Code (In DAL):
public ELClass FillData(String Id)
{
Int32 ID= Convert.ToInt32(Id);
var q = (from schedules in context.FeeSchedules
where schedules .ScheduleId == ID
select schedules );
return q.SingleOrDefault();
}

Accessing User in Entity partial class via OnContextCreated()?

All of my tables have common audit fields: modifiedBy,modifiedDateTime, etc.
I would like to have these automatically set, and can set most of them with the following code:
partial class myEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(Entities_SavingChanges);
}
private void Entities_SavingChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry> objectStateEntries =
from ose
in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
where ose.Entity != null
select ose;
var auditDate = DateTime.Now;
var auditUser = System.Web.HttpContext.Current.User.Identity.Name;//I wish
foreach (ObjectStateEntry entry in objectStateEntries)
{
ReadOnlyCollection<FieldMetadata> fieldsMetaData = entry.CurrentValues.DataRecordInfo.FieldMetadata;
FieldMetadata modifiedField = fieldsMetaData.Where(f => f.FieldType.Name == "ModifiedBy").FirstOrDefault();
if (modifiedField.FieldType != null)
{
string fieldTypeName = modifiedField.FieldType.TypeUsage.EdmType.Name;
if (fieldTypeName == PrimitiveTypeKind.String.ToString())
{
entry.CurrentValues.SetString(modifiedField.Ordinal, auditUser);
}
}
}
}
}
The problem is that there doesn't appear to be any way to get access to the current user. The app is intranet only, using Windows auth.
Is there a way to either pass in a parameter, or get access to the HttpContext (which doesn't seem like it would be a good idea, but I'm stuck)? Is there a way to populate the EventArgs with information?
Check out the section where the poster has overridden the SaveChanges method (6th code box down on the page). This way you can pass in the UserID and perform your audit and not have to use an event handler.

Resources