Dane Balia
Dane Balia

Reputation: 5367

WPF UserControl Populate Controls

When (what event) should the controls (Combos, Drop-Downs) be populated in a WPF User Control?

Currently I'm using UserControl_Loaded, but this fires more than once, and on a development machine, produces inconsistent results.

public UserControl_Load(x, x)
{
   if(!this.Loaded)
   {
     //populate controls here
   } 
}

If this is the best practice, then I will try resolve that problem; but I'm more interested in when (what event) is best used for populating controls?

Thanks

Given Sheridan's answer, I found this wonderful blog post for those who may be looking a great tutorial on how to correctly databind in WPF (Blog)

Upvotes: 0

Views: 340

Answers (1)

Sheridan
Sheridan

Reputation: 69959

Rather than handling events to populate your controls, try the data binding way instead:

First create a collection property in a class (view model) that implements the INotifyPropertyChanged interface:

// You need to implement the `INotifyPropertyChanged` interface properly here
public ObservableCollection<YourDataType> Items { get; set; }

Then you can fill it from code called in the constuctor, or in a Command handler in response to some UI action:

Items = GetSomeItems();

Now, if you have defined a Binding for this property to a UI collection control, then the UI will be automatically updated:

<ListBox ItemsSource="{Binding Items}">
    ...
</ListBox>

As long as you set the DataContext property of the view to an instance of your view model:

DataContext = new SomeViewModel();

Finally, I'd advise you to take a look at the Data Binding Overview page on MSDN for further information.

Upvotes: 1

Related Questions