Sugee
Sugee

Reputation: 79

How to bind property of child class from itemscontrol of parent class

I have an items control binded to list of parent class. I need to bind the properties of the child class in the data template.

These are the classes I have

public class Parent {

    private string _name;
     public string Name
        {
            get { return _name; }
            set
            {
                if (Equals(value, _name)) return;
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
}


public class Child1 : Parent{

    private string _prob1;
     public string Prob1
        {
            get { return _prob1; }
            set
            {
                if (Equals(value, _prob1)) return;
                _prob1= value;
                OnPropertyChanged(nameof(Prob1));
            }
        }
}

public class Child2 : Parent{

    private string _prob2;
     public string Prob2
        {
            get { return _prob2; }
            set
            {
                if (Equals(value, _prob2)) return;
                _prob2= value;
                OnPropertyChanged(nameof(Prob2));
            }
        }
}

and in my view model I have an observable collection of Parent class

 public ObservableCollection<Parent> ParentList { get; set; }

and my xaml code

 <ItemsControl  ItemsSource="{Binding ParentList }">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate  
              DataType="domainObject:Child1">

<TextBlock Text="{Binding Name}" Margin="5" IsEnabled="False"  HorizontalAlignment="Center" Height="22" Background="Transparent" />

<TextBlock Text="{Binding Prob1}" Margin="5"HorizontalAlignment="Center" Height="22" />


I want to bind the 2. textbox to a property of child class.

Is there any simple way to fix this problem?

Upvotes: 0

Views: 1396

Answers (1)

Clemens
Clemens

Reputation: 128061

In case the ParentList collection contains elements of different derived types (either Child1 or Child2) you should have different DataTemplates, which would automatically be chosen by their DataType property.

You may declare these DataTemplates in the Resources of the ItemsControl:

<ItemsControl ItemsSource="{Binding ParentList}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type domainObject:Child1}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" ... />
                <TextBlock Text="{Binding Prob1}" ... />
            </StackPanel>
        </DataTemplate>
        <DataTemplate DataType="{x:Type domainObject:Child2}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" ... />
                <TextBlock Text="{Binding Prob2}" ... />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

Upvotes: 1

Related Questions