wpf DataGrid的用法

           在wpf中DataGrid类似于web中的GrilView,用来绑定数据列表的,用法很类似,也可以定义模板,灵活显示,看一下代码

           xaml:

          

 <DataGrid Name="dgDataSource" IsReadOnly="True"  Width="725">
                <DataGrid.Resources>
                    <Style TargetType="{x:Type DataGridRow}">
                        <Setter Property="Height" Value="95"/>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.Columns> 
                    <DataGridTextColumn Width="300" Header="广告标题" Binding="{Binding Title,Mode=OneWay}" CellStyle="{StaticResource dgvCellLeft10}" />
                    <DataGridTemplateColumn Header="广告图片" Width="250">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>                                        
<Image Height="78" Source="{Binding AdPhoto,Mode=OneWay}" HorizontalAlignment="Left" Margin="10,0,0,0" Name="image1"
Stretch="Fill" VerticalAlignment="Top" Width="190" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Width="150" Header="添加时间" Binding="{Binding AddTime,Mode=OneWay,StringFormat='yyyy-MM-dd HH:mm:ss'}"
CellStyle="{StaticResource dgvCellLeft10}"/> </DataGrid.Columns> <DataGrid.ContextMenu> <ContextMenu> <!--<Separator />--> <MenuItem x:Name="mitmDelete" Header="删除广告" Click="mitmDelete_Click"> <MenuItem.Icon> <Image Source="/Fin;component/Icons/Error.ico" /> </MenuItem.Icon> </MenuItem> <MenuItem x:Name="mitmUpdate" Header="修改广告" Click="mitmUpdate_Click"> <MenuItem.Icon> <Image Source="/Fin;component/Icons/Error.ico" /> </MenuItem.Icon> </MenuItem> <!--<Separator />--> </ContextMenu> </DataGrid.ContextMenu> </DataGrid>

在这里定义了模板,因为图片需要显示在Image中,其中MenuItem作用就是右击,效果如下

后台代码中,采用了泛型集合IList<实体>的绑定方法

 /// <summary>
        /// 实体
        /// </summary>
        private WebShopAdService.ShopAd Entity
        {
            get { return this.dgDataSource.CurrentItem as WebShopAdService.ShopAd; }
        }
  /// <summary>
        ///  初始化数据
        /// </summary>
        private void InitializeData() 
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" AddUser='"+PassData.CurrentUserId+"'");
            pager.PageSize = 2;
            WebShopAdService.ShopAd[] shopAdList = webShopAd.isSelectPaging(strSql.ToString(), pager.PageSize, pager.PageCurrent, out _dataTotal);
            IList<WebShopAdService.ShopAd> list = new List<WebShopAdService.ShopAd>(shopAdList);
            foreach (var item in list)
            {
                ShopAd model = item as ShopAd;
                model.AdPhoto = ReadConfig.GetValue("webDomain") + model.AdPhoto;
            }  
             dgDataSource.ItemsSource = list;
        }

可以通过Entity.ID类似的获取其他属性

 

posted @ 2013-01-15 11:21  双魂人生  阅读(7479)  评论(1编辑  收藏  举报