开发者

Idiomatic way to declare DataForm's current item?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜