Silverlight: How to do data entry to a collection?
I have an app for tracking expenses. Users add new expenses through a form. Expenses are kept in a collection.
I'm new to Silverlight, and not sure exactly what the best way to set up my app is. Currently, I have a DataGrid
with columns that I've defined to format the members of the ICollection
nicely. In the code behind, I've specified a collection to be the ItemSource
of the data grid.
Each expense is represented by a class called ExpenseInfo
.
To add new expenses, I was thinking that I would make a new instance of ExpenseInfo
, and data bind the values in the form inputs to it. Then, when the user clicks submit, that instance would be added to the collection.
I'm not entirely sure how to do this. Do I specify it in Xaml? In code-behind?
Also, 开发者_如何学Pythonright now I'm adding ExpenseInfo
items to the backing collection, but the data grid doesn't change. (Perhaps my binding mode is wrong?) This works in the page constructor:
CurrentExpensesGrid.ItemsSource = expenses;
ExpenseInfo initialExpense = new ExpenseInfo() { Cost = "23", Date = DateTime.Now, WhoPaid = "foo", Name = "bar" };
initialExpense.WhoOwes.Add("baz");
initialExpense.WhoOwes.Add("ftw");
expenses.Add(initialExpense);
However, the following doesn't work in the add button click event handler:
expenses.Add(newExpense);
expenses.Add(new ExpenseInfo() {Cost="2", Name="fje", Date = DateTime.Now, WhoPaid="foe"});
And by "doesn't work", I mean that the new items do not appear in the data grid.
You can make use of observablecollection in silverlight ,
1-Collection which you are using in ItemSource can be an observablecollection of ExpenseInfo.
2- There must be a button called 'Add More Expense'. When user click on this button , you can create a new object of ExpanseInfo and add it to the collection.
3- observablecollection listens for the changes so a new row will be added in the grid.
精彩评论