ImageSource from Resources

2019-08-02 19:05发布

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条回答
我只想做你的唯一
2楼-- · 2019-08-02 20:11

Your ImagePath property should be

ImagePath="pack://application:,,,/<your resources>/yourImage.png";
查看更多
登录 后发表回答