E
E
Egor2015-05-05 11:14:20
.NET
Egor, 2015-05-05 11:14:20

How to automatically create a UIElement when setting the Content property?

I have classes in the program whose objects I would like to edit into interfaces. An arbitrary number of classes, respectively, with a different set of editable fields. Editing of these objects should take place in one window.
The Content property of any panel in the window is "associated" with the source of such objects and, depending on the type of the current object, a control is automatically generated.
Those. I want to define classes whose objects could be placed in the Content property, as a result of which, in the interface, a control would be created and not the result of calling the ToString method. How can this be implemented?
For example, you can make these classes the heirs of the panel or user control, in which case, as I understand it, the problem will be solved. But I would like to limit myself to the implementation of some interface or method, because by definition, these classes are neither a panel nor a user control.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2015-05-06
@humster

As far as I understand, an ItemsControl with a template described in the ItemTemplate based on your class is suitable for you. You can specify multiple templates for each class or describe an ItemsTemplateSelector that will select a template based on any criteria.
In fact, the template just generates the UIElement you need.
The principles of operation are as follows: XAML describes an ItemsControl with the ItemTemplate templates you need.
In an ItemsControl, use the Items property to add/remove items to the list, or you can (and most often should) use an ItemsSource. You can add elements of different classes. For each object, the corresponding template will be searched and UIElements will be generated based on it.
Reading:
Understanding Data Templates
A small example:

<ItemsControl ItemsSource="{Binding Path=MixedList}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:MyFirstClass}">
            <StackPanel><TextBox Text="{Binding Name}" /></StackPanel>
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:MySecondClass}">
              <StackPanel>
                 <TextBox Text="{Binding Property1}" />
                 <TextBox Text="{Binding Property2}" />
               </StackPanel>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question