Rag*_*ghu 4 wpf datagrid datagridtemplatecolumn
BitmapImage im = new BitmapImage();
string path1 = @"C:\abc.png";
im.UriSource=new Uri(path1);
DataGridTemplateColumn one = new DataGridTemplateColumn();
this.dataGrid1.Columns.Add(one);
Run Code Online (Sandbox Code Playgroud)
现在我必须在datagridTemplateColumn中添加BitmapImage im.
如何在列中添加图像?
Moh*_*mad 15
在代码中使用控件模板很难.在WPF中,标准且有效的方法是在XAML中创建模板布局.然后,如果您需要将任何数据传递给控件,则使用数据绑定.除了极少数情况,您通常不需要在代码中构建模板.
要使用XAML获得与上述相同的效果,请编写:
<DataGrid x:Name="dataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="file:///C:\abc.png" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
如果图像路径必须是每个网格行的动态,您可以像这样修改它:
<DataGrid x:Name="dataGrid1" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding ImageFilePath}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
这里是用一些数据填充网格的示例代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<MyDataObject> list = new List<MyDataObject>();
list.Add(new MyDataObject() { ImageFilePath = new Uri("file:///c:\\abc.png") });
list.Add(new MyDataObject() { ImageFilePath = new Uri("file:///c:\\def.png") });
dataGrid1.ItemsSource = list;
}
}
public class MyDataObject
{
public Uri ImageFilePath { get; set; }
}
Run Code Online (Sandbox Code Playgroud)