nitefrog
nitefrog

Reputation: 1830

WPF XAML Generics Class Binding

Can you bind in XAML to a Class that takes a type T?

If I have a class myCLASS<T> and I want to bind a List<myClass<int>> to XAML can you do it?

Or do you have to write a wrapper class newMyClass: myClass<int> and then bind the XAML to newMyClass?

Thanks.

Upvotes: 1

Views: 5422

Answers (2)

Rick Sladkey
Rick Sladkey

Reputation: 34240

The WPF binding subsystem supports any type of object, structures, classes, generic classes and even dynamic objects. All that matters is that the instances have properties.

You cannot create generic classes in the resources of a typical WPF application because the object creation syntax does not support it. Nevertheless, objects that are created in code-behind, in your view-model, or by services (even if they are instances of generic types or nested generic types), can still participate in binding.

Here's an example based on the question. Here's some XAML for a window:

<Grid>
    <ListBox ItemsSource="{Binding}" Padding="10">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding X}"/>
                    <TextBlock Text=" , "/>
                    <TextBlock Text="{Binding Y}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

and here's a generic class that resembles a Point class:

class myClass<T>
{
    public T X { get; set; }
    public T Y { get; set; }
}

and here is some code-behind to support the binding in the XAML above:

void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = new List<myClass<int>>
    {
        new myClass<int> { X = 1, Y = 2 },
        new myClass<int> { X = 3, Y = 4 },
    };
}

and this is what it looks like:

Generic Binding

We created instances of the generic class in the code-behind but bound to that data using XAML.

Upvotes: 1

vcsjones
vcsjones

Reputation: 141638

XAML 2009 supports it using x:TypeArguments, but it isn't an comfortable option at the moment since it isn't supported by Microsoft's XAML to BAML compiler. For XAML 2009, you would have to read the XAML using XamlReader yourself, but then lose greater functionality like a code behind. You're best off doing as you suggested at the moment.

Upvotes: 1

Related Questions