tags:

views:

29

answers:

1

I'm using a DataForm. So far, I've found two ways to specify its current item: a static resource, or in the code behind.

Init in code behind:

expenseDataForm.CurrentItem = new ExpenseInfo();

To save an entry:

    private void expenseDataForm_EditEnded(object sender, DataFormEditEndedEventArgs e)
    {
        if (e.EditAction.Equals(DataFormEditAction.Commit))
        {
            // cast `sender` instead of hardcoding it to expenseDataForm?
            expenses.Add(expenseDataForm.CurrentItem as ExpenseInfo);
            expenseDataForm.CurrentItem = new ExpenseInfo();
        }
    }

Using resources instead:

<local:ExpenseInfo x:Key="newExpense"/>
<!-- ... -->

<df:DataForm CurrentItem="{StaticResource newExpense}" ... />

Then, when I go to save, I get problems:

    private void expenseDataForm_EditEnded(object sender, DataFormEditEndedEventArgs e)
    {
        if (e.EditAction.Equals(DataFormEditAction.Commit))
        {
            // cast `sender` instead of hardcoding it to expenseDataForm?
            expenses.Add(expenseDataForm.CurrentItem as ExpenseInfo);
            LayoutRoot.Resources["newExpense"] = new ExpenseInfo(); // crashes here
        }
    }

Is this stylistically wrong? I've read that static resources are supposed to be alive through the application, although these expense info objects clearly wouldn't be. Should I just go with the code-behind route?

+1  A: 

The crash is because you cannot assign values to resource dictionaries using an existing key. They do not support replacement.

You need to call LayoutRoot.Resources.Remove("newExpense") first. Then you can assign a fresh value.

On a broader issue, you should really look into the MVVM pattern. The current selection would then become a property of the ViewModel. Using a resource for your data is not recommended. Code behind is a very slight improvement, but still has problems.

Enough already