<Window x:Class="DataGridExam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataGridExam"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:ImageConverter x:Key="ImageConverter"></local:ImageConverter>
    </Window.Resources>
    <Grid>
        <DataGrid Name="gridProducts" AutoGenerateColumns="False" FrozenColumnCount="1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Product" Width="175" Binding="{Binding Path=ModelName}"></DataGridTextColumn>
                <DataGridTextColumn Header="Price" Binding="{Binding Path=UnitCost,StringFormat={}{0:C}}"></DataGridTextColumn>
                <DataGridTextColumn Header="ModelNumber" Binding="{Binding Path=ModelNumber}"></DataGridTextColumn>
                <DataGridTextColumn Header="Description" Width="400" Binding="{Binding Path=Description}">
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                            <Setter Property="TextWrapping" Value="Wrap"></Setter>                            
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
                <DataGridTextColumn Header="CategoryID" IsReadOnly="True" Binding="{Binding Path=CategoryID}"></DataGridTextColumn>
                <DataGridTemplateColumn Header="Image" IsReadOnly="True">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Stretch="None" Source="{Binding Path=ProductImage,Converter={StaticResource ImageConverter}}"></Image>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
             </DataGrid.Columns>
        </DataGrid>
        
    </Grid>

</Window>

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 DataGridExam
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            gridProducts.ItemsSource = StoreDB.GetProducts();
        }
    }

}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class StoreDB
    {
        public static string connString = Properties.Settings.Default.ConnectionString;

        public static Product GetProductByID(int id)
        {
            Product p = null;
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID", id);
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    p = new Product()
                    {
                        CategoryID = (int)reader[1],
                        ModelNumber = reader[2].ToString(),
                        ModelName = reader[3].ToString(),
                        ProductImage=reader[4].ToString(),
                        UnitCost = (decimal)reader[5],
                        Description = reader[6].ToString()
                    };
                }
                return p;

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void UpdateProductByID(int ProductID,Product p)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("UpdateProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID",ProductID);
            cmd.Parameters.AddWithValue("@CategoryID",p.CategoryID);
            cmd.Parameters.AddWithValue("@ModelNumber",p.ModelNumber);
            cmd.Parameters.AddWithValue("@ModelName",p.ModelName);
            cmd.Parameters.AddWithValue("@ProductImage",p.ProductImage);
            cmd.Parameters.AddWithValue("@UnitCost",p.UnitCost);
            cmd.Parameters.AddWithValue("@Description",p.Description);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void InsertProduct(Product p)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("InsertProduct", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CategoryID", p.CategoryID);
            cmd.Parameters.AddWithValue("@ModelNumber", p.ModelNumber);
            cmd.Parameters.AddWithValue("@ModelName", p.ModelName);
            cmd.Parameters.AddWithValue("@ProductImage", p.ProductImage);
            cmd.Parameters.AddWithValue("@UnitCost", p.UnitCost);
            cmd.Parameters.AddWithValue("@Description", p.Description);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void DeleteProductByID(int id)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("DeleteProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID", id);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static ObservableCollection<Product> GetProducts()
        {
            ObservableCollection<Product> products = new ObservableCollection<Product>();
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProducts", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    products.Add(new Product()
                    {
                        ProductID = (int)reader[0],
                        CategoryID = (int)reader[1],
                        ModelNumber = reader[2].ToString(),
                        ModelName = reader[3].ToString(),
                        ProductImage = reader[4].ToString(),
                        UnitCost = (decimal)reader[5],
                        Description = reader[6].ToString()
                    });
                }
                return products;

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static DataSet GetProductsAndCategories()
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProducts", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            SqlDataAdapter adatper = new SqlDataAdapter(cmd);
            adatper.Fill(ds, "Products");
            cmd.CommandText = "GetCategories";
            adatper.Fill(ds, "Categories");
            DataRelation rel = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]);
            return ds;
        }
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class Product
    {
        public int ProductID { get; set; }
        public int CategoryID { get; set; }
        public string ModelNumber { get; set; }
        public string ModelName { get; set; }
        public string ProductImage { get; set; }
        public decimal UnitCost { get; set; }
        public string Description { get; set; }

        public Product(int CategoryID = 0, string ModelNumber = "",
            string ModelName = "", string ProductImage = "", decimal UnitCost=0,string Description="")
        {
            this.CategoryID = CategoryID;
            this.ModelNumber = ModelNumber;
            this.ModelName = ModelName;
            this.ProductImage = ProductImage;
            this.UnitCost = UnitCost;
            this.Description = Description;
        }

    }

}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace DataGridExam
{
    [ValueConversion(typeof(string), typeof(BitmapImage))]
    public class ImageConverter : IValueConverter
    {
        string rootPath = Directory.GetCurrentDirectory();
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string imagePath = Path.Combine(rootPath, value.ToString());
            return new BitmapImage(new Uri(imagePath));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    
}

WPF DataGrid自定义列DataGridTextColumn.ElementStyle和DataGridTemplateColumn.CellTemplate的更多相关文章

  1. WPF DataGrid某列使用多绑定后该列排序失效,列上加入 SortMemberPath 设置即可.

    WPF DataGrid某列使用多绑定后该列排序失效 2011-07-14 10:59hdongq | 浏览 1031 次  悬赏:20 在wpf的datagrid中某一列使用了多绑定,但是该列排序失 ...

  2. WPF DATAGrid 空白列 后台绑定列 处理

    原文:WPF DATAGrid 空白列 后台绑定列 处理 AutoGenerateColumns <DataGrid x:Name="dataGrid" Margin=&qu ...

  3. WPF DataGrid 操作列 类似 LinkButton

    WPF中没有类似LinkButton,所以只有运用Button及样式来实现LinkButton. DataGrid 操作列 实现 多个类似LinkButton按钮: 具体实现代码如下: <Dat ...

  4. wpf DataGrid CheckBox列全选

    最近在wpf项目中遇到当DataGrid的header中的checkbox选中,让该列的checkbox全选问题,为了不让程序员写自己的一堆事件,现写了一个自己的自定义控件 在DataGrid的 &l ...

  5. WPF DataGrid自定义样式

    微软的WPF DataGrid中有很多的属性和样式,你可以调整,以寻找合适的(如果你是一名设计师).下面,找到我的小抄造型的网格.它不是100%全面,但它可以让你走得很远,有一些非常有用的技巧和陷阱. ...

  6. EasyUI Datagrid 自定义列、Foolter及单元格编辑

    1:自定义列,包括 Group var head1Array = []; head1Array.push({ field: 'Id', title: 'xxxx', rowspan: 2 }); he ...

  7. WPF DataGrid 自定义样式 MVVM 删除 查询

    看到很多小伙伴在找Dategrid样式 就分享一个 ,有不好的地方 请指出 代码部分都加了注释  需要的可以自己修改为自己需要的样式 源码已经上传 地址:  https://github.com/YC ...

  8. WPF报表自定义通用可筛选列头-WPF特工队内部资料

    由于项目需要制作一个可通用的报表多行标题,且可实现各种类型的内容显示,包括文本.输入框.下拉框.多选框等(自定的显示内容可自行扩展),并支持参数绑定转换,效果如下: 源码结构 ColumnItem类: ...

  9. C# WPF DataGrid 隔行变色及内容居中对齐

    C# WPF DataGrid 隔行变色及内容居中对齐. dqzww NET学习0     先看效果: 前台XAML代码: <!--引入样式文件--> <Window.Resourc ...

随机推荐

  1. Strut2与Hibernate的一个web分页功能

    代码没有进行过多的封装,可能看起来有点action代码部分,hibernate在这里只起到了一个查询记录集的作用. import java.util.ArrayList; import java.ut ...

  2. warning C4996: 'fopen': This function or variable may be unsafe.(_CRT_SECURE_NO_WARNINGS)

    在 windows 平台下的 visual studio IDE,使用 fopen 等 CRT 函数(C runtime library(part of the C standard library) ...

  3. Quartz.NET 3.0.7 + MySql 实现动态调度作业+动态切换版本+多作业引用同一程序集不同版本+持久化+集群(一)

    原文:Quartz.NET 3.0.7 + MySql 实现动态调度作业+动态切换版本+多作业引用同一程序集不同版本+持久化+集群(一) 前端时间,接到领导任务,写了一个调度框架.今天决定把心路历程记 ...

  4. [React Router v4] Redirect to Another Page

    Overriding a browser's current location without breaking the back button or causing an infinite redi ...

  5. 5.Maven和Eclipse整合(两种方式进行插件的安装),Maven相关设置,Eclipse下创建Maven项目

     1  第一种方式是:在连网的情况下.通过在helpàInstall下安装. 新的地址是:http://download.eclipse.org/technology/m2e/releases 2 ...

  6. Eclipse使用异常——tomcat启动

    Eclipse使用异常--tomcat启动 一:问题描写叙述 Eclipse刚上手.非常多地方与Myeclipse不一样的地方.比方tomcat的使用.真心的蛋疼. 环境:JDK7.TOMCAT7.E ...

  7. 【b301】神经网络

    神经网络(NOIP2003第1题) Time Limit: 1 second Memory Limit: 50 MB [问题背景] 人工神经网络(Artificial Neural Network)是 ...

  8. AndroidMainifest标签使用说明3——&lt;activity-alias&gt;

    格式: <activity-alias android:enabled=["true" | "false"] android:exported=[&quo ...

  9. FPGA综合优化

    1 速度和面积 在全面优化水平将达到速度和面积RTL要利用逻辑拓扑的优势. 供FPGA由于在后端而言缺乏知识,门级优化.普通情况下更高的速度要求更高的并行性以及更大的面积,可是在某些特殊情况下并非这样 ...

  10. 深入浅出MFC:对话框消息路由

    [appmodul.cpp] extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstanc ...