Search code examples
wpfwpf-controlswpfdatagridwpftoolkit

Loading Buttons on window loaded event depending on Number of User


enter image description hereWe have WPF application, We want functionality like below. I want one form, which will contain Users name & one Button in front of each User. Means if Database have 10 Users, it will bring this 10 user when window load , & in front of each user there will be show button.


Solution

  • You can use ListBox and create a DataTemplate containing your Label and Button

    Example:

    Xaml:

    <Window x:Class="WpfApplication16.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication16"
            Title="MainWindow" Height="350" Width="525" Name="UI">
        <Window.Resources>
    
            <!-- DataTemplate for User object -->
            <DataTemplate DataType="{x:Type local:User}" >
                <Border CornerRadius="3" BorderBrush="Black" BorderThickness="1" Margin="2" >
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding UserName}" Width="100"/>
                        <Button Content="Show User" Width="100" Margin="2"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </Window.Resources>
    
        <Grid DataContext="{Binding ElementName=UI}">
            <!-- The ListBox -->
            <ListBox ItemsSource="{Binding Users}" />
        </Grid>
    </Window>
    

    Code:

    public partial class MainWindow : Window
    {
        private ObservableCollection<User> _users = new ObservableCollection<User>();
    
        public MainWindow()
        {
            InitializeComponent();
    
            // Load users
            for (int i = 0; i < 10; i++)
            {
                Users.Add(new User { UserName = "User " + i });
            }
        }
    
        public ObservableCollection<User> Users
        {
            get { return _users; }
            set { _users = value; }
        }
    }
    
    public class User
    {
        public string UserName { get; set; }
    }
    

    Result

    enter image description here