简体   繁体   中英

C# TabControl binding with linq groupby statement in WPF

I am new to WPF and I am trying to bind a List of grouped object to a tabControl and I just manage to get halfway there

Here is my C# Code In the constructor :

IEnumerable<Validation> validations = ReflectiveEnumerator.GetEnumerableOfType<Validation>().Where(validation => validation.IsActive);

tabControl.ItemsSource = validations.GroupBy(validation => validation.TabName); 

and my xaml code is :

<TabControl x:Name="tabControl" Margin="10,10,10,37" ItemsSource="{Binding Groups}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <WrapPanel>
                <TextBlock Text="{Binding ValidationName}"/>
            </WrapPanel>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

and so I get a tab by group which is what I was expecting but within my wrap panel I only have 1 ValidationName per Tab, I was expecting multiple ones. what is missing to have the content panel Iterate through my group.

When I don't group by I have multiple tabItem with the same Name and that's not what I'm looking for.

My Validation class looks like :

public class Validation
{
    public string ValidationName {get; private set;}
    public string TabName{get; private set;}
    public bool IsActive{get; private set;}
}

You could use an ItemsControl in the ContentTemplate of the TabControl:

<TabControl x:Name="tabControl" Margin="10,10,10,37" ItemsSource="{Binding Groups}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ValidationName}" Margin="10"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

The above sample markup will display a TextBlock per item in each group in a WrapPanel inside each TabItem.

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