【问题标题】:Set BitmapImage dynamically via Binding using a converter in XAML使用 XAML 中的转换器通过绑定动态设置 BitmapImage
【发布时间】:2020-06-18 16:00:50
【问题描述】:

我有以下xaml(请注意,这是在 Microsoft Workflow Foundation 活动中使用的,包含在 <sap:ActivityDesigner.Icon> 中。希望没关系,但我想我会提到它。)

<DrawingBrush>
    <DrawingBrush.Drawing>
        <ImageDrawing>
            <ImageDrawing.Rect>
                <Rect Location="0,0" Size="16,16" ></Rect>
            </ImageDrawing.Rect>
            <ImageDrawing.ImageSource>
                <BitmapImage UriSource="MyImage.png"/>
            </ImageDrawing.ImageSource>
        </ImageDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

我需要在运行时更改 UriSource,所以我想我会使用这样的转换器:

<DrawingBrush>
    <DrawingBrush.Drawing>
        <ImageDrawing>
            <ImageDrawing.Rect>
                <Rect Location="0,0" Size="16,16" ></Rect>
            </ImageDrawing.Rect>
            <ImageDrawing.ImageSource>
                <BitmapImage UriSource="{Binding Path=MyObject, Converter={StaticResource NameToImageConverter}}"/>
            </ImageDrawing.ImageSource>
        </ImageDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

但如果尝试将其绑定到我的对象并使用转换器,则会收到以下错误:

提供的 DependencyObject 不是此 Freezable 的上下文

请注意,它不会影响我的转换器。

我找到了The provided DependencyObject is not a context for this Freezable WPF c#,我认为这会有所帮助,但无济于事。

为 BitmapImage 对象设置名称时

<BitmapImage Name="MyBitmapImage"/>

我以为我可以通过代码进行设置,但我仍然遇到同样的错误。

我不知道自从最初看到这个之后我做了什么,但最初我收到一个错误,说我应该使用 beginInit 和 endInit。抱歉没有确切的错误,因为我无法复制它。

关于如何实现这一点的任何想法?

谢谢。

【问题讨论】:

  • &lt;ImageDrawing ImageSource="{Binding ...}"/&gt; 使用返回 ImageSource 而不是 Uri 的转换器怎么样?
  • 如果您的 MyObject 应该在运行时更改其值并通知 UI,您的方法无论如何都不会起作用,因为 BitmapImage 只能由其 UriSource 属性初始化一次。以后无法更改。
  • @Clemens 非常感谢您的建议!你能坚持这个作为答案吗?它可以很好地在 ImageDrawing 上设置 ImageSource。我不得不进一步研究如何加载图像,但它现在可以很好地与转换器一起使用。

标签: wpf xaml binding workflow-foundation-4


【解决方案1】:

BitmapImage 实现ISupportInitialize 接口,只能初始化一次,以后不能更改。如果您的 MyObject 应该在运行时更改其值并通知 UI,那将无法正常工作。

您可以将绑定更改为

<ImageDrawing
    ImageSource="{Path=MyObject, Converter={StaticResource NameToImageConverter}}"
    Rect="0,0,16,16" />

并使绑定转换器返回 BitmapImage 而不是 Uri:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    ...
    string uri = ...;
    return new BitmapImage(new Uri(uri));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多