I have a GridColumn with FieldName=="Image". Image is a property type of BitmapImage in MyClass, which is assigned in constructor.
XAML:
<dxg:GridColumn Header="MyImage" ReadOnly="True" VisibleIndex="0" AllowResizing="False" Width="20*"
HorizontalHeaderContentAlignment="Center"
FieldName="Image">
<dxg:GridColumn.EditSettings>
<dxe:ImageEditSettings MaxWidth="15" />
</dxg:GridColumn.EditSettings></dxg:GridColumn>
MyClass:
public class MyClass
{
public MyClass(ImageType imageType)
{
Image = imageType switch
{
ImageType.T1=> new BitmapImage(new Uri(@"pack://application:,,,/MyProject;component/Assets/Images/information-blue-red.png", UriKind.RelativeOrAbsolute)),
ImageType.T2=> new BitmapImage(new Uri(@"pack://application:,,,/MyProject;component/Assets/Images/information-blue.png", UriKind.RelativeOrAbsolute)),
ImageType.T3=> new BitmapImage(new Uri(@"pack://application:,,,MyProject;component/Assets/Images/information-red.png", UriKind.RelativeOrAbsolute)),
ImageType.T4=> new BitmapImage(new Uri(@"pack://application:,,,/MyProject;component/Assets/Images/information-white.png", UriKind.RelativeOrAbsolute)),
_ => default
};
}
public BitmapImage Image { get; set; }
}
So I fill GridControl with ItemsSource of that type. When I execute the program - refreshing method is called at first and everything is OK, I mean that each cell contains needing image. But if I refresh it again(calling such method, which is asynchronous) - ItemsSource is being filled again, and MyClass objects are being created without any problems, but I'm getting an error, that an object is in another thread, so it is inaccessible, after refreshing. I don't know exactly, which object, but I'm sure, that's related to Image property, because I've tested that without such column, and result was OK.
ERROR:
System.InvalidOperationException: "The calling thread cannot access this object because another thread owns this object."
Your MyClass constructor seems to be called in a thread other than the UI thread. It should hence take care for making the BitmapImage in the Image property cross-thread accessible by freezing it.
The property should also be readonly, or it should fire a change notification when it is set.
And there is no need to set UriKind.RelativeOrAbsolute
because a Pack URI is always absolute.
public MyClass(ImageType imageType)
{
var name = imageType switch
{
ImageType.T1 => "information-blue-red.png",
ImageType.T2 => "information-blue.png",
ImageType.T3 => "information-red.png",
ImageType.T4 => "information-white.png",
_ => null
};
if (name != null)
{
var uri = new Uri(
"pack://application:,,,/MyProject;component/Assets/Images/" + name);
var image = new BitmapImage(uri);
image.Freeze(); // here
Image = image;
// alternatively, call Image = BitmapFrame.Create(uri);
}
}
public ImageSource Image { get; }