简体   繁体   中英

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

  • Either creating a UserControl with a DependencyProperty of type ObservableCollection<UserDefinedFieldBase> and use some appropriate container with a TemplateSelector for the derived classes
  • Work/implement a ItemsControl and ItemsSource without going through a custom DependencyProperty

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM