问题
My Problem:
I need a DataGrid with 4 columns. One of them should show an Image. I used DataGridTemplateColumn for this and the others are simple TextColumns. I need different images per row and this is why I need to bind them with the rest of my property's in my Class.
I've tried using a property of type Image while setting
AutoGenerateColumns="true"
and I've tired binding the images path with a string property filled with the path from my project resources but this didn't work either.
Does anyone know how to solve this ?
My Code behind is:
public List<MyClass> MyCollection {get; set;}//<--- This is what I bind !
public class MyClass
{
public string A { get; set; }
public string ImagePath { get; set; }
public int X { get; set; }
public string User { get; set; }
}
My XAML is this:
<Window.Resources>
<CollectionViewSource x:Key="EntryCollection" Source="{Binding Path=MyCollection , Mode=OneWay}"/>
</Window.Resources>
<DataGrid ItemsSource="{Binding Source={StaticResource EntryCollection}, Mode=OneWay}" SelectedItem="{Binding Path=SelectedEntry, Mode=TwoWay}"
IsReadOnly="true"
AutoGenerateColumns="False"
SelectionUnit="FullRow"
SelectionMode="Extended"
HorizontalAlignment="Stretch"
Grid.Column="0"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
Width="Auto">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Width="16" Height="16" Source="{Binding Path=ImagePath, Mode=OneWay}" VerticalAlignment="Top" HorizontalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="User" Binding="{Binding Path=User, Mode=OneWay}" Width="Auto" />
<DataGridTextColumn Header="StringA" Binding="{Binding Path=A, Mode=OneWay}" Width="Auto" />
<DataGridTextColumn Header="INT X" Binding="{Binding Path=X, Mode=OneWay}" Width="Auto" />
Thanks in advance!
回答1:
Your ImagePath property should be
ImagePath="pack://application:,,,/<your resources>/yourImage.png";
来源:https://stackoverflow.com/questions/29772088/imagesource-from-resources