<Window x:Class="CollectionBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:data="clr-namespace:ClassLibrary;assembly=ClassLibrary"
        xmlns:local="clr-namespace:CollectionBinding"
        Title="MainWindow" Height="449.904" Width="358.716">
    <Window.Resources>
        <local:ImageConverter x:Key="ImageConverter"></local:ImageConverter>
        <DataTemplate DataType="{x:Type data:Product}">
            <Border Margin="3" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>
                    <TextBlock Margin="3" FontWeight="Bold" Text="{Binding Path=ModelNumber}"></TextBlock>
                    <TextBlock Grid.Row="1" Margin="3" FontWeight="Bold" Text="{Binding Path=ModelName}"></TextBlock>
                    <Image Grid.Row="2" Margin="3" Height="100" Width="100" Source="{Binding Path=ProductImage,Converter={StaticResource ImageConverter}}"></Image>
                </Grid>
            </Border>
        </DataTemplate>
    </Window.Resources>
 
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ListBox Margin="3" Grid.Row="0" Name="lstProducts" Height="120" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible">
           
            
        </ListBox>
        <StackPanel Margin="3" Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Margin="3" MinWidth="100" Name="btnGetProducts" Click="btnGetProducts_Click_1">GetProducts</Button>
        </StackPanel>
        <Grid Margin="3" Name="grid" Grid.Row="2" DataContext="{Binding ElementName=lstProducts,Path=SelectedItem}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBlock Margin="3" Grid.Row="0" Grid.Column="0">CategoryID:</TextBlock>
            <TextBox Name="txtCategoryID" Margin="3" Grid.Row="0" Grid.Column="1" Text="{Binding Path=CategoryID}"></TextBox>

            <TextBlock Margin="3" Grid.Row="1" Grid.Column="0">ModelNumber:</TextBlock>
            <TextBox Name="txtModelNumber" Margin="3" Grid.Row="1" Grid.Column="1" Text="{Binding Path=ModelNumber}"></TextBox>

            <TextBlock Margin="3" Grid.Row="2" Grid.Column="0">ModelName:</TextBlock>
            <TextBox Name="txtModelName" Margin="3" Grid.Row="2" Grid.Column="1" Text="{Binding Path=ModelName}"></TextBox>

            <TextBlock Margin="3" Grid.Row="3" Grid.Column="0">ProductImage:</TextBlock>
            <TextBox Name="txtProductImage" Margin="3" Grid.Row="3" Grid.Column="1" Text="{Binding Path=ProductImage}"></TextBox>

            <TextBlock Margin="3" Grid.Row="4" Grid.Column="0">UnitCost:</TextBlock>
            <TextBox Name="txtUnitCost" Margin="3" Grid.Row="4" Grid.Column="1" Text="{Binding Path=UnitCost}">
                
            </TextBox>
            
            <TextBox Name="txtDescription" Margin="3" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" TextWrapping="Wrap"
                     Text="{Binding Path=Description}" ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBox>
        </Grid>
    </Grid>
</Window>

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 CollectionBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public ObservableCollection<Product> products;

        private void btnGetProducts_Click_1(object sender, RoutedEventArgs e)
        {
            products = StoreDB.GetProducts();
            lstProducts.ItemsSource = products;
        }

    }

}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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();
            }
        }
    }

}

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 CollectionBinding
{
    [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 数据模板使用值转换器的更多相关文章

  1. WPF数据模板样式选择器

    在使用数据模板样式选择器时,不能设置ItemContainerStyle的属性值,如果设置了该值,那么数据模板样式选择器会失去作用. 在使用数据模板样式选择器时,首先要创建数据模板样式选择器对象,此对 ...

  2. WPF数据模板和控件模板

     WPF中有控件模板和数据模板,控件模板可以让我们自定义控件的外观,而数据模板定义了数据的显示方式,也就是数据对象的可视结构,但是这里有一个问题需要考虑,数据是如何显示出来的?虽然数据模板定义了数 ...

  3. WPF数据模板(7)

    数据模板常用在3种类型的控件, 下图形式: 1.Grid这种列表表格中修改Cell的数据格式, CellTemplate可以修改单元格的展示数据的方式. 2.针对列表类型的控件, 例如树形控件,下拉列 ...

  4. WPF数据模板中绑定事件不触发问题

    今天比较闲,做一个练手的项目,结果在xaml中写了一个用户的数据模板后,在其中的某个Canvas上绑定了一个鼠标左击的事件,结果调试的时候,无论怎么点击都不跳到断点那里,百思不得其解. 之后尝试不绑定 ...

  5. WPF数据模板的数据触发器的使用

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  6. WPF 数据模板DataType属性的使用,不用指定ItemTemplate

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  7. WPF 数据模板的使用

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  8. WPF备忘录(3)如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter

    一.如何从 Datagrid 中获得单元格的内容 DataGrid 属于一种 ItemsControl, 因此,它有 Items 属性并且用ItemContainer 封装它的 items. 但是,W ...

  9. WPF教程十五:数据模板的使用(重发)

    数据模板 数据模板是一段如何显示绑定在VM对象的XAML代码.数据模板可以包含任意元素的组合,基于Binding来显示不同的信息. 在实际的开发中数据模板的应用场景很多,同样一个控件可以根据不同的绑定 ...

随机推荐

  1. jquery获取选中select的文本,值等

    jquery获取select选择的文本与值获取select :获取select 选中的 text :    $("#ddlregtype").find("option:s ...

  2. 什么是uuid以及uuid在java中的使用

    什么是UUID?UUID是Universally Unique Identifier的缩写,它是在一定的范围内(从特定的名字空间到全球)唯一的机器生成的标识符.UUID具有以下涵义: 经由一定的算法机 ...

  3. 使用JSONP解决跨域问题-代码示例

    前段时间用JSONP解决了跨域问题,现在不用了,把代码思路记下来,今后说不定还用得上. JS代码 //查询公告数据 function recentpost(){ $.getJSON(cmsUrl+&q ...

  4. [Angular] Working with FormArray

    'FormArray' can work with array of 'FormGroup' or 'FormControl'. form = new FormGroup({ stock: new F ...

  5. html 横线的代码

    第一种: <hr style=" height:2px;border:none;border-top:2px dotted #185598;" />   园点虚线 he ...

  6. UItextfield 动态限制输入的字数

    @property (nonatomic, strong) UITextField *txtName; - (void)viewDidLoad { [super viewDidLoad]; //UIC ...

  7. 解决gdb 调试 core 文件函数名显示为问号的问题

    关于gdb调试core文件总是一堆问号的问题 问题描写叙述:已经在编译选项中增加了-g,可是查看core文件时.还是一堆问号,使用的命令为:gdb -c core 解决方式:因为gdb -c core ...

  8. 【BZOJ 1037】[ZJOI2008]生日聚会Party

    [题目链接]:http://www.lydsy.com/JudgeOnline/problem.php?id=1037 [题意] [题解] /* 设f[i][j][k][l] 表示前i个人中,有j个男 ...

  9. [think in java] 第8章 多态

    多态 "封装"通过合并特征和行为来创建新的数据类型. "多态"的作用则是消除类型之间的耦合关系. 方法调用绑定 定义:将一个方法调用同一个方法主题关联起来被称为 ...

  10. TensorFlow 实战(二)—— tf.train(优化算法)

    Training | TensorFlow tf 下以大写字母开头的含义为名词的一般表示一个类(class) 1. 优化器(optimizer) 优化器的基类(Optimizer base class ...