Search code examples
c#wpfvisual-studio-2010prism-4

Creating a grid dynamically


I've a table in a database where I need to show all the rows's content (as a TextBlock) and to the right of each TextBlock I need to show a TextBox so the user can enter a value (a number) for each row and also I need to be able to change the color of any TextBox when the value provided by the user is negative.

Can someone give me a clue with this?

PD: I'm using WPF with Prism 4 and MVVM pattern and VS2010 Ultimate


Solution

  • I won't give you a complete solution, but I can point you in the right direction.

    I start by creating a data structure that contains properties for Name and Value, and that implements INotifyPropertyChanged for Property Change notification.

    Next in the ViewModel (or possibly Model), I would make would be an ObservableCollection<MyDataObject>, and populate it with the data from the database.

    In the XAML, I would use an ItemsControl bound to the collection, and overwrite the ItemTemplate to render each item as either a Horizontal StackPanel or a Grid, containing the Label and TextBox

    For the TextBox.Foreground property, I would bind it to the same value that TextBox.Text is bound to, except I'd also use a IValueConverter in the binding which checks to see if the value is above or below 0, and returns the correct color. Since it is a binding, it will automatically update whenever the value changes.

    <TextBox Text="{Binding Value}"
             Foreground="{Binding Value, Converter={StaticResource MyCustomConverter}}" />