【问题标题】:How to bind <DrawingImage> from resource dictionary using MVVM and Data Binding如何使用 MVVM 和数据绑定从资源字典中绑定 <DrawingImage>
【发布时间】:2021-08-31 10:50:25
【问题描述】:

请帮忙。我在 ResourceDictionary &lt;DrawingImage x:Key="MyDrawingImage"&gt; 中有一个 XAML 图像。如何使用 MVVM 将其绑定到 ?列表项有文字和图片。

public class MyItemViewModel {
    public string TextToDisplay { get; set; }
    
    public string? ImageToDisplay { get; set;}    ??????            
}

问题是,从资源字典中绑定图像最优雅的方法是什么?

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border CornerRadius="10">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="3*" />
                                <RowDefinition Height="2*" />
                            </Grid.RowDefinitions>
                            <Image Source="{Binding ImageToDisplay}" ???????? />
                            <TextBlock Grid.Row="1" 
                                       Text="{Binding TextToDisplay}"/>

                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    终于,我找到了答案。也许这对某人会派上用场:

    public class DsItemViewModel {
        public DsItemViewModel(string name, string? drawingImageResourceKey = null) {
            Name = name;                
            if (drawingImageResourceKey != null)
                Image = Application.Current.FindResource(drawingImageResourceKey) as DrawingImage;
        }
        
        public string Name { get; }
    
        public DrawingImage? Image { get; }
    }
    

    【讨论】:

    • 通常最好避免让视图模型暴露特定的 UI 元素。它使您以后可以更灵活地更改它。因此,尽管您的解决方案确实有效,但将这一切都保留在 XAML 中可能是一个更好的主意。您可以将您的 XAML Image 更改为如下所示:&lt;Image Source="{Binding Source={StaticResource MyDrawingImage}}"/&gt;
    • 我不能写 ,因为我有可重用的控件,它在我的应用程序的不同位置显示不同的图像和标签列表。
    • 那我很困惑。您的问题是说您想将 Image 绑定到资源“MyDrawingImage* 您提出的解决方案与我建议的相同,除了后面的代码。或者您是说您有多个这样的 DrawingImage 对象具有多个键的资源和视图模型可能会得到其中的任何一个?
    • 是的,准确的。我的资源字典中有多个图像,并且我希望对具有不同图像和标签的不同列表具有单个可重用控件。
    • 啊,明白了。那是有道理的。
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2023-03-04
    相关资源
    最近更新 更多