Search code examples
c#wpfdata-bindingdatagridwpf-controls

WPF ItemsControl is not rendering UI


Here is the UI code to loop string array: MainWindow.xaml

<ItemsControl ItemsSource="{Binding sideMenuCollection}">
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Border BorderThickness="2" BorderBrush="Black" >
            <StackPanel Orientation="Horizontal" Height="50">
                <TextBlock Text="&#xf0e4;" Margin="10,0,0,0" FontFamily="{StaticResource FontAwesome}" FontSize="35" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                <TextBlock Text="{Binding}" FontSize="26" Margin="10,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" Name="smb_dashboard" MouseDown="smb_dashboard_MouseDown"></TextBlock>
            </StackPanel>
        </Border>
    </DataTemplate>
</ItemsControl.ItemTemplate>

MainWindow.xaml.cs

public List<string> sideMenuCollection = new List<string> {
            "Dashboard", 
            "Customers",
            "Items", 
            "Reports"
        };

No idea what's going wrong here ?

It should be creating sidemenus in red area.

enter image description here


Solution

  • In order to make

    ItemsSource="{Binding sideMenuCollection}"
    

    work, sideMenuCollection must be a property, not a field, and the DataContext of the Window should be set to the Window instance, which owns the property:

    public partial class MainWindow : Window
    {
        public List<string> sideMenuCollection { get; } = new List<string>
        {
            "Dashboard",
            "Customers",
            "Items",
            "Reports"
        };
    
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
    }