【问题标题】:How to set border background imagebrush in code-behind如何在代码隐藏中设置边框背景图像刷
【发布时间】:2017-01-05 09:44:57
【问题描述】:

我有一个在 Windows 应用程序中使用的 WPF 自定义用户控件。控件有一个边框作为主元素,这个边框有一个默认的背景图片。下面的代码显示了如何将此图像设置为默认值。默认图像是资源元素 (Images/BlueRoad.jpg)。

我希望能够使用图像文件名作为字符串(例如“C:\Pictures\myCustomPic.bmp”)以编程方式更改边框背景的图像。我需要使用 Visual Basic 在代码隐藏中执行此操作,除非在 XAML 中有非常简单的方法可以执行此操作。无论哪种方式,图片都会加载到控件的启动代码中。

我对 WPF 了解不多,这只是应用程序的一小部分,所以希望尽可能简单快速地完成这项工作。

非常感谢!

<Border Name="mainBorder" Opacity="1" BorderBrush="SteelBlue" BorderThickness="3">
    <Border.Background>
        <ImageBrush  ImageSource="Images/BlueRoad.jpg"></ImageBrush>
    </Border.Background>

     Grid and other stuff goes here...

 </Border> 

【问题讨论】:

    标签: .net wpf code-behind imagebrush


    【解决方案1】:
    using System;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    ...
    var imagePath = @"pack://application:,,,/MyProject;component/Resources/BorderImage.png";
    ImageBrush brush = new ImageBrush(new BitmapImage(new Uri(imagePath, UriKind.Absolute)));
    MyBorder.Background = brush;
    

    【讨论】:

      【解决方案2】:

      您可以使用 ImageBrush 和 BitmapImage 将画笔设置为边框背景 首先,您使用 uri 创建 BitmapImage 并将此 BitmapImage 发送到 ImageBrush 并将 ImageBrush 分配给边框背景

      【讨论】:

      • 嗨 Ali Kiani - 感谢您的评论和对我迟到的回复表示歉意。问题是我似乎无法在代码中访问此图像刷。此外,我要将其设置为的图像是运行时加载的图像,而不是资源文件。就像我说的 - 我不是 WPF 专家,我希望一些专家可能只是有一个代码 sn-p 让我解决问题。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多