【问题标题】:How set default image?如何设置默认图像?
【发布时间】:2011-05-22 19:29:29
【问题描述】:

数据网格:

<sdk:DataGridTemplateColumn>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Tag="{Binding photo}" MinWidth="50"  Source="{Binding photo, Converter={StaticResource ConvertNullImageKey}}"/>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

如果值不是 uri,则转换器从 ImageResource.noimage 返回 iamge。但是这个位图...如何在位图上返回 URI?

public class ConvertNullImage : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                try
                {
                    Uri uri = new Uri(value.ToString(), UriKind.Relative);
                    return uri;
                }
                catch { return new Uri(ImageResource.noimage); }
            }

            public object ConvertBack(object value, Type targetType, object parameter,
                                      CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }

【问题讨论】:

    标签: c# silverlight datagrid converter


    【解决方案1】:

    Image.Source 属性不是Uri 类型,而是ImageSource 类型,请参阅MSDN:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.image.source%28VS.95%29.aspx

    当您在 XAML 中设置 Image.Source 时,XAML 解析器会巧妙地将您的 URI 转换为 ImageSource

    所以 - 你需要在你的价值转换器中创建一个BitmapImage。请参阅此相关问题:

    Image UriSource and Data Binding

    【讨论】:

      【解决方案2】:

      ImageSource 属性需要 ImageSource,而不是 URI。感谢TypeConverter,这在 xaml 中有效。您可以从路径创建 BitmapImage 并返回,如 here 所示。

      如果我理解正确,问题的第二部分是您想将(作为默认值)绑定到资源文件中的图像。如果是这样,这里是article on how to do that on MSDN

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-31
        • 2019-06-13
        • 2019-11-21
        相关资源
        最近更新 更多