ImageSource from Resources

非 Y 不嫁゛ 提交于 2019-12-11 13:05:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!