Search code examples
c#wpfxamldata-bindingitemssource

Bind Count of ItemsSource of an ItemsControl in a TextBlock using WPF


I want to bind a Count of ItemsSource of an ItemsControl in a TextBlock using WPF.

Have a Look into my tried Code

<Menu>
    <MenuItem>
        <MenuItem.Header>
            <TextBlock Text="{Binding Path=(ItemsControl.ItemsSource.Item, RelativeSource={RelativeSource TemplatedParent}}" />
        </MenuItem.Header>

        <ItemsControl ItemsSource="{Binding PersonCollection}">
            <ItemsControl.ItemTemplate>
                <DataTemplate >
                    <StackPanel Orientation="Horizontal" Margin="2" MinWidth="100">
                        <TextBlock Text="{Binding Value.Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </MenuItem>
</Menu>

Note: I need to get the count based on ItemsControl ItemsSource not by the Collection.Count Property. Kindly assist me.


Solution

  • This is the solution:

     <Menu>
            <MenuItem>
                <MenuItem.Header>
                    <TextBox Text="{Binding ElementName=ItemsControl, Path=Items.Count,  Mode=OneWay}" />
                </MenuItem.Header>
    
                <ItemsControl x:Name="ItemsControl"
                              ItemsSource="{Binding Items}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal"
                                        Margin="2"
                                        MinWidth="100">
                                <TextBlock Text="{Binding Value.Text}" />
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </MenuItem>
        </Menu>
    

    Does it work for you?