How do I show image in wpf datagrid column programmatically?

前端 未结 3 677
春和景丽
春和景丽 2020-12-11 22:33

I want to add two columns in wpf datagrid one image & one text columns dynamically.

Xaml code :

 

        
相关标签:
3条回答
  • 2020-12-11 22:36

    If you want to Set an Image in a DataGrid Column HEADER, only programmatically, you can perform like this:

    ImageSource image = new BitmapImage(new Uri(@"C:/téléchargement.jpg", UriKind.RelativeOrAbsolute));
    
    Style style = new Style(typeof(DataGridColumnHeader));
    FrameworkElementFactory factory = new FrameworkElementFactory(typeof(Image));
    factory.SetValue(Image.SourceProperty, image);
    factory.SetValue(Image.StretchProperty, Stretch.Uniform);
    style.Setters.Add(new Setter { Property = TemplateProperty, Value = new ControlTemplate { TargetType = typeof(DataGridColumnHeader), VisualTree = factory } });
    
    DataZone.Columns[5].HeaderStyle = style;
    
    

    You can use this method for any type ( Ex : TextBlock , Label, ...), or create a more complex controlTemplate

    0 讨论(0)
  • 2020-12-11 22:52

    Use DataGridTemplateColumn. Define cell template in Window.Resources and use FindResource() to set column's CellTemplate property.

    Hope this helps.

    0 讨论(0)
  • 2020-12-11 22:57

    As Anvaka said, you can Use DataGridTemplateColumn. In C# you can add create DataGridTemplateColumn as this, Here i have added a CheckBox in to the DataGridTemplateColumn.

    DataGridTemplateColumn col1 = new DataGridTemplateColumn();
    col1.Header = "MyHeader";
    FrameworkElementFactory factory1 = new FrameworkElementFactory(typeof(Image));
    Binding b1 = new Binding("Picture");
    b1.Mode = BindingMode.TwoWay;
    factory1.SetValue(Image.SourceProperty, b1);
    DataTemplate cellTemplate1 = new DataTemplate();
    cellTemplate1.VisualTree = factory1;
    col1.CellTemplate = cellTemplate1;
    datagrid.Columns.Add(col1);
    

    Here Picture is a property of ImageSource type in the class which collection is assigned to ItemsSource of DataGrid.

    0 讨论(0)
提交回复
热议问题