Chia sẻ

Nội dung

Giới thiệu

Trong bài này csharpcanban.com sẽ hướng dẫn các bạn lấy giá trị của Listview trong WPF như trên hình. Các bạn thực hiện theo các bước sau đây:

Các bước thực hiện

Bước 1: Khởi tạo một dự án mới

Bước 2: Thêm Listview vào dự án

<ListView Background="#FFFFFFFF" Margin="10" x:Name="lvUsers" Grid.Row="4" Grid.Column="1" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <EventSetter Event="MouseDoubleClick"  Handler="ListViewItem_MouseDoubleClick"/>
                        </Style>
                    </ListView.ItemContainerStyle>
                    <ListView.View>
                        <GridView>
                            <GridViewColumn>
                                <GridViewColumn.Header>
                                    <CheckBox/>
                                </GridViewColumn.Header>
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Margin="7" Tag="{Binding Number}"/>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn >
                            <GridViewColumn Header="STT" Width="60" DisplayMemberBinding="{Binding Number}" />
                            <GridViewColumn Header="Tiêu đề" Width="500" DisplayMemberBinding="{Binding Title}" />
                            <GridViewColumn Header="Thống kê" Width="150">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <TextBlock Margin="7" Text="{Binding Summary}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>

Bước 3: Tải dữ liệu lên Listview 

– Tạo một Class mới

public class Projects
    {
        public string Number { get; set; }
        public string Title { get; set; }
        public string Summary { get; set; }
    }

– Tải dữ liệu lên Listview

public MainWindow()
{
            InitializeComponent();
            List<Projects> items = new List<Projects>();
            for (int i = 1; i <= 10; i++)
            {
                items.Add(new Projects() { Number = i.ToString(), Title = "Title -" + i.ToString(), Summary = "Xem" });
            }
            lvUsers.ItemsSource = items;
}

Bước 4: Lấy dữ liệu từ Listview khi nhấp đúp chuột vào một dòng

private void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
            var item = ((Projects)lvUsers.SelectedItem).Number;
            if (item != null)
            {
                MessageBox.Show(item.ToString());
            }
}

Bước 5: Chạy ứng dụng và thử nhấp đúp chuột vào một dòng bất kỳ của Listview.

Lưu ý: Trong các bước trên thì bước 4 là khó nhất. Mọi câu hỏi hãy đặt vào trong phần bình luận dưới đây. Csharpcanban.com sẽ trả lời chi tiết.

Xem thêm  [WPF] Thêm Tabs mới vào TabControl khi chạy chương trình

Mã nguồn

– Trong tệp MainWindow.xaml.cs

using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;

namespace Dashboard
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<Projects> items = new List<Projects>();
            for (int i = 1; i <= 10; i++)
            {
                items.Add(new Projects() { Number = i.ToString(), Title = "Title -" + i.ToString(), Summary = "Xem" });
            }
            lvUsers.ItemsSource = items;
        }
       
        private void GridBarraTatulo_MouseDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void Btn_WindowMaximize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Maximized;
        }

        private void Btn_CreateNewProject_Click(object sender, RoutedEventArgs e)
        {
            CreateNew open_new = new CreateNew();
            open_new.ShowDialog();
        }

        private void Btn_quit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var item = ((Projects)lvUsers.SelectedItem).Number;
            if (item != null)
            {
                MessageBox.Show(item.ToString());
            }
        }
    }

    public class Projects
    {
        public string Number { get; set; }
        public string Title { get; set; }
        public string Summary { get; set; }
    }
}

– Tệp MainWindow.xaml

<Window x:Class="Dashboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Dashboard"
        xmlns:materialdesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d" Width="1024" Height="600"
        Title="MainWindow" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid Grid.Column="1" Grid.Row="1" Background="#FFF1E6E6">
            <ScrollViewer>
                <ListView Background="#FFFFFFFF" Margin="10" x:Name="lvUsers" Grid.Row="4" Grid.Column="1" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <EventSetter Event="MouseDoubleClick"  Handler="ListViewItem_MouseDoubleClick"/>
                        </Style>
                    </ListView.ItemContainerStyle>
                    <ListView.View>
                        <GridView>
                            <GridViewColumn>
                                <GridViewColumn.Header>
                                    <CheckBox/>
                                </GridViewColumn.Header>
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Margin="7" Tag="{Binding Number}"/>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn >
                            <GridViewColumn Header="STT" Width="60" DisplayMemberBinding="{Binding Number}" />
                            <GridViewColumn Header="Tiêu đề" Width="500" DisplayMemberBinding="{Binding Title}" />
                            <GridViewColumn Header="Thống kê" Width="150">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <TextBlock Margin="7" Text="{Binding Summary}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>
            </ScrollViewer>
        </Grid>

        <Grid Grid.Row="1" Background="#FFDAD1D1">
            <Grid.RowDefinitions>
                <RowDefinition Height="100" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid.Effect>
                <DropShadowEffect BlurRadius="20" Color="#FFE0BFBF" />
            </Grid.Effect>
            <Grid Background="#FFC86CF3">
                <TextBlock Text="DASHBOARD" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="WS Simple Gallifreyan" Foreground="#FFBC96EA" FontSize="16" />
            </Grid>
            <StackPanel Grid.Row="1">
                <Button x:Name="btn_CreateNewProject" Click="Btn_CreateNewProject_Click"  Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="ViewDashboard"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="DỰ ÁN MỚI" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="Account"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="PERFIL" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="ContentPaste"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="TABBELAS" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="TShirtCrew"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="TABBELAS" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="WalletProduct"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="PRODUTOS" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="TruckDelivery"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="FORNECEDORES" />
                    </Grid>
                </Button>
                <Button Margin="10" Background="#FF8522BD" BorderBrush="#FF8522BD">
                    <Grid Width="150">
                        <materialdesign:PackIcon Kind="Settings"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="CONFIGURATION" />
                    </Grid>
                </Button>
            </StackPanel>
        </Grid>
        <Grid x:Name="GridBarraTatulo" Grid.ColumnSpan="2" Background="#FF8522BD" MouseDown="GridBarraTatulo_MouseDown">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="10,0">
                <Button Width="25" Height="25" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White">
                    <materialdesign:PackIcon Kind="Bell" />
                </Button>
                <Button Width="25" Height="25" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White">
                    <materialdesign:PackIcon Kind="Account" />
                </Button>
                <Button x:Name="btn_WindowMaximize" Click="Btn_WindowMaximize_Click" Width="25" Height="25" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White">
                    <materialdesign:PackIcon Kind="WindowMaximize" />
                </Button>
                <Button x:Name="btn_quit" Click="Btn_quit_Click" Width="25" Height="25" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White">
                    <materialdesign:PackIcon Kind="Power" />
                </Button>
            </StackPanel>
        </Grid>
    </Grid>
</Window>

Tải mã nguồn

Tải mã nguồn Listview

Xem thêm  [WPF] Hướng dẫn xoay Rectangle trong WPF

Chúc các bạn thành công. !!!

ĐĂNG KÝ MUA HÀNG

    Email (*)

    Điện thoại (*)

    Tên sản phẩm/Dịch vụ:


    Chia sẻ

    Trả lời

    Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *