Daniel Kress
Daniel Kress

Reputation: 57

How to build a WPF control containing other controls based on a bound list

I have got a ViewModel that looks like

public class MyViewModel
{
    public ObservableCollection<UserDefinedFieldBase> CustomFields { get; }
}
public class UserDefinedFieldBase
{
    public Point CustomLocation { ... }
}
public class CustomTextField : UserDefinedFieldBase
{
    public string Text { ... }
}

So every possible type of field has a own type and includes a location (which is customizable by the user, so it's part of the viewModel, not the view.

Question part: What would be the best approach to implement the control? I thought about

Upvotes: 1

Views: 347

Answers (1)

mm8
mm8

Reputation: 169270

It depends on what the purpose of the control is, how it is supposed to work and how the UI is supposed to look like.

If you want to display several UserDefinedFieldBase objects in the view you should use an ItemsControl that binds to the CustomFields property of the view model. You could still add the ItemsControl to a UserControl with several other dependency properties though.

If you only want to display a list of UserDefinedFieldBase, you probably don't need a UserControl at all. You could just use an ItemsControl and define the appearance of each item using the ItemTemplate.

So you should use an ItemsControl but whether or not you need to create a UserControl is a bit unclear based on the information you have provided. If you want to display something more than just an ItemsControl with a list of items, you could wrap the ItemsControl in a UserControl that adds several other elements as appropriate.

Upvotes: 1

Related Questions