开发者

Silverlight Data Binding

I'm writing an app where users enter records. I have a class that represents a record. Binding it to text fields works.

MainPage.xaml.cs:

    public MainPage()
    {
        InitializeComponent();

        // newExpense is of type ExpenseInfo
        LayoutRoot.DataContext = newExpense;
    }

ExpenseInfo.cs:

public class ExpenseInfo
{

    public String Name { get; set; }

    // ...
}

MainPage.xaml:

<TextBox Text="{Binding Name, Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="13,205,0,0" Name="NameTextBox" VerticalAlignment="Top" Width="74" />

This works to get and set the input. Two questions:

What if I have a ListBox, whose members I'm trying to represent with an ICollection in ExpenseInfo? Can I automatically bind it? What if I'm using a ComboBox instead?

Sometimes, I want ExpenseInfo to change the input controls. How can I do this? (For example, if the user types "3$0" in the "Cost" text box, I'd like to automatically change it 开发者_如何学Cto "$30".)

Thanks. I'm new to Silverlight 4.


If you can bind an individual record to a text field, a standard collection of those records will bind in much the same way to a collection field. So yes, you can do exactly that, although the details for ComboBox vary. This article has a lot more information on data binding in WPF, but it sounds like you have a good basic handle on it.

To automatically correct wrong data, read this article about the Validation process. It explains how to set up your own system to detect and report errors in user input. Handling invalid data doesn't have to just show a warning in the UI- you could write back to the .Value field of your TextBox to automatically correct the input if you know how to do it, but it's up to you to write the code both to detect what's wrong and figure out what's right.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜