1

I have two objects with different properties,

eg

class foo
{
     int age;
     string name;
}

class bar
{
     string kind;
     int length;
}

I have a gridview usercontrol that can easily bind one class to its rows and columns but I don't want to make another usercontrol just for the second class, id rather reuse the same control for displaying the data, how can I do this in WPF databinding?

Id rather you didn't post code examples, just point me in the direction, I have looked at data templates but they seem to want the property to bind to, in this case I have two different objects.

regards

1 Answer 1

2

It is not the UserControl, nor the GridView where you define what your data items will look like, so you can easily display items from different classes in one UserControl. Instead, you define how each class should be rendered by declaring DataTemplates:

<DataTemplate DataType="{x:Type YourPrefix:foo}">
    <StackPanel>
        <TextBlock Grid.Row="0" Text="{Binding age}" />
        <TextBlock Grid.Row="1" Text="{Binding name}" />
    </StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type YourPrefix:bar}">
    <StackPanel>
        <TextBlock Grid.Row="0" Text="{Binding kind}" />
        <TextBlock Grid.Row="1" Text="{Binding length}" />
    </StackPanel>
</DataTemplate>

Of course, you'd need to use a collection of type object if you want to be able to put different types of objects in it:

public ObservableCollection<object> Items { get; set; }

...

Items = GetFoos();
// Or Items = GetBars();

...

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

Reading the Data Templating Overview page on MSDN should help you understand this all better. However, I wouldn't recommend this approach as you'd continually have to cast objects back to their proper types. You're much better off declaring different UserControls for each data type being displayed or edited.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.