WPF DataGrid show data from Postgresql

-- Table: public.geoboundaries-usa-adm1_simplified

-- DROP TABLE IF EXISTS public."geoboundaries-usa-adm1_simplified";

CREATE TABLE IF NOT EXISTS public."geoboundaries-usa-adm1_simplified"
(
    gid serial NOT NULL,
    shapename character varying(44) COLLATE pg_catalog."default",
    shapeiso character varying(5) COLLATE pg_catalog."default",
    shapeid character varying(23) COLLATE pg_catalog."default",
    shapegroup character varying(3) COLLATE pg_catalog."default",
    shapetype character varying(4) COLLATE pg_catalog."default",
    geom geometry(MultiPolygon,4326),
    CONSTRAINT "geoboundaries-usa-adm1_simplified_pkey" PRIMARY KEY (gid)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."geoboundaries-usa-adm1_simplified"
    OWNER to postgres;
-- Index: geoboundaries-usa-adm1_simplified_geom_idx

-- DROP INDEX IF EXISTS public."geoboundaries-usa-adm1_simplified_geom_idx";

CREATE INDEX IF NOT EXISTS "geoboundaries-usa-adm1_simplified_geom_idx"
    ON public."geoboundaries-usa-adm1_simplified" USING gist
    (geom)
    TABLESPACE pg_default;

 

 

 

image

 

 

 

select * from public."geoboundaries-usa-adm1_simplified";

image

 

Install-Package Npgsql;

 

 

<Window x:Class="WpfApp9.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:WpfApp9"
        mc:Ignorable="d"
        Title="Data From Postgresql" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding GeoCollection}"
                  Margin="5"
                  BorderBrush="Cyan"
                  BorderThickness="2"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  UseLayoutRounding="True"
                  HeadersVisibility="Column">
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="30"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Red"/>
                            <Setter Property="FontWeight" Value="ExtraBold"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
        </DataGrid>
    </Grid>
</Window>


using Npgsql;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp9
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        private static string connectStr = "Host=localhost;Port=5432;Database=GISDB;Username=postgres;Password=password";

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                LoadDataFromPostgresqlTableAsync();
            }
        }

        private void LoadDataFromPostgresqlTableAsync()
        {
            //            string sql = @"SELECT gid,shapename,shapeiso,shapeid,shapegroup,shapetype,ST_AsText(geom) as geom_wkt
            //FROM public.geoboundaries-usa-adm1_simplified";

            string sql = @"
SELECT 
    gid,
    shapename,
    shapeiso,
    shapeid,
    shapegroup,
    shapetype,
    ST_AsText(geom) as geom_wkt
FROM public.""geoboundaries-usa-adm1_simplified"";
";

            using (var conn = new NpgsqlConnection(connectStr))
            {
                conn.Open();
                using var cmd = new NpgsqlCommand(sql, conn);
                using var reader = cmd.ExecuteReader();

                List<GeoBoundaryAdm1> items = new List<GeoBoundaryAdm1>();
                while (reader.Read())
                {
                    items.Add(new GeoBoundaryAdm1
                    {
                        Gid = reader.GetInt32("gid"),
                        Shapename = reader["shapename"] as string,
                        Shapeiso = reader["shapeiso"] as string,
                        Shapeid = reader["shapeid"] as string,
                        Shapegroup = reader["shapegroup"] as string,
                        Shapetype = reader["shapetype"] as string,
                        GeomWkt = reader["geom_wkt"] as string
                    });
                }
                GeoCollection = new ObservableCollection<GeoBoundaryAdm1>(items);
            }
        }

        private ObservableCollection<GeoBoundaryAdm1> geoCollection;
        public ObservableCollection<GeoBoundaryAdm1> GeoCollection
        {
            get
            {
                return geoCollection;
            }
            set
            {
                if (value != geoCollection)
                {
                    geoCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

    }

    public class GeoBoundaryAdm1
    {
        public int Gid { get; set; }
        public string? Shapename { get; set; }
        public string? Shapeiso { get; set; }
        public string? Shapeid { get; set; }
        public string? Shapegroup { get; set; }
        public string? Shapetype { get; set; }
        public string? GeomWkt { get; set; }
    }

}

 

 

 

 

image

 

 

 

image

 

posted @ 2026-10-01 19:58  FredGrit  阅读(2)  评论(0)    收藏  举报