【问题标题】:WPF Custom Control with Image.带有图像的 WPF 自定义控件。
【发布时间】:2012-05-29 16:27:06
【问题描述】:

我对@9​​87654321@ 还很陌生,目前遇到了问题。

我有一个包含两个项目的解决方案,第一个项目是一个自定义控件库,里面有一个自定义窗口表单控件。第二个项目是使用我的自定义窗口窗体的 WPF 应用程序。

除了表单图标外,一切正常。在 WPF 应用程序项目中,我将窗口图标属性设置为 /ProjectTwoNameSpace;component/Resources/Images/Film.ico,并在 WPF 自定义控件中尝试以这种方式显示该图像:

<Image Grid.Column="0" Margin="3" Width="27" Height="27">
     <Image.Source>
        <BitmapImage UriSource="{Binding Path=Icon}" />
     </Image.Source>
 </Image>

但这不起作用,我在运行时收到一个错误,提示必须为我的&lt;Image&gt; 标签设置属性UriSourceStreamSource

有人可以帮助我吗?我认为这只是一个 WPF 新手问题。

【问题讨论】:

    标签: wpf image xaml custom-controls


    【解决方案1】:

    BitmapImageUriSource 属性无法像您显示的那样设置,因为它是 Uri 类型,并且您正试图将其设置为字符串。我想说完成你正在做的最简单的方法是将你的 Image.Source 绑定到 Icon,然后将字符串转换为位图 Image 对象。假设你的控件在一个窗口中,这看起来像这样

    <Window.Resources>
        <converters:StringToBitmapImageConverter x:Key="stringToBitmapImageConverter" />
    </Window.Resources>
    
    ...
    
    <Image Grid.Column="0" Margin="3" Width="27" Height="27"
        Source="{Binding Path=Icon, Converter={StaticResource stringToBitmapImageConverter}}">
    </Image>
    

    然后转换器看起来像:

    class StringToBitmapImageConverter: IValueConverter
    {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri(value as string);
            image.EndInit();
    
            return image;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        #endregion
    }
    

    【讨论】:

    • 您的解决方案很好,但您关于 UriSource“无法通过数据绑定设置”的说法是不正确的。您可以将 UriSource 绑定到 Uri 类型的属性。你不能做的是将它绑定到没有转换器的字符串属性。
    • 我在尝试粘贴 标记时出错,提示在窗口类型中找不到属性资源。我想在哪里粘贴这个 XAML 代码?
    • 它对我不起作用,我没有收到编译错误,但图像不存在。图标属性设置正确,因为我可以在任务栏中看到图标,但在我的自定义控件中看不到。也许问题出在我的图标属性设置为 WPF 应用程序命名空间并且在 WPF 控件库命名空间中找不到?
    猜你喜欢
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多