【问题标题】:How to bind image to GridColumn?如何将图像绑定到 GridColumn?
【发布时间】:2020-07-23 19:40:56
【问题描述】:

我有一个 FieldName=="Image" 的 GridColumn。 Image是MyClass中BitmapImage的一个属性类型,在构造函数中赋值。

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>

我的班级:

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; }
}

所以我用该类型的 ItemsSource 填充 GridControl。当我执行程序时 - 首先调用刷新方法并且一切正常,我的意思是每个单元格都包含需要的图像。但是如果我再次刷新它(调用这样的方法,它是异步的) - ItemsSource 再次被填充,并且 MyClass 对象正在被创建而没有任何问题,但是我得到一个错误,一个对象在另一个线程中,所以它刷新后无法访问。我不知道具体是哪个对象,但我敢肯定,这与 Image 属性有关,因为我已经在没有这样的列的情况下进行了测试,结果还可以。

错误:

System.InvalidOperationException:“调用线程无法访问此对象,因为另一个线程拥有此对象。”

【问题讨论】:

  • 考虑编辑问题以询问单个问题。您可以单独提出另一个问题,如果需要,请参阅前面的问题。另请参阅minimal reproducible example
  • @Sinatr 我可以在 90 分钟问一次,所以我决定把两个问题合并起来,因为它们是相互关联的
  • Related。每个帖子一个问题是一个规则,否则您的问题将因为“需要更多关注”而被关闭,而您根本得不到答案。
  • @Sinatr,我可以编辑这个问题留下一个吗?
  • 为您的错误使用 dispatcher.invoke

标签: c# wpf devexpress


【解决方案1】:

您的 MyClass 构造函数似乎是在 UI 线程以外的线程中调用的。因此,它应该注意通过冻结它来使 Image 属性中的 BitmapImage 跨线程访问。

该属性也应该是只读的,或者它应该在设置时触发更改通知。

而且不需要设置UriKind.RelativeOrAbsolute,因为Pack URI 总是绝对的。

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; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 2013-02-24
    • 2013-06-25
    • 2012-06-20
    • 2015-01-10
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多