WPF:处理图像
我想创建以下功能:我希望能够在窗口上显示图像(如果提供)或线性渐变画笔(如果图像不存在)。我想出了两种方法:
创建
Border
并将ImageBrush
应用于边框Background
属性,如果 提供了图像Uri
,如果没有提供LinearGradientBrush
。这很容易 实现:视图模型将通过图像提供边框背景属性 画笔或线性渐变画笔。但有一个大问题:如果图像尺寸 不适合边框尺寸,图像变形,这是我希望避免的。是 有一种方法可以设置 ImageBrush 并保留图像尺寸比率,即 应用类似Stretch = Stretch.Uniform
?创建一个
边框
和一个图像
在里面。然后,创建数据触发器 边框,如果图像Uri
(视图模型中的属性)为null
,则设置 边框的Background
为LinearGradientBrush
并将其留空,如果 否则。我尝试创建这个,但数据触发器从未理解null
案件。Image
也存在问题,因为如果提供了null
ImageSource
属性,抛出异常。代码如下所示:<边框宽度=“130”高度=“170”> <边框.样式> <样式TargetType =“边框”> <样式.触发器>
<设置器.值> <图像名称=“图像”拉伸=“统一”> <图像.来源> <位图图像 DecodePixelWidth =“{绑定元素名称=图像,路径=宽度}” UriSource="{绑定路径=图像}" />
实现此类功能的最佳和最简单的方法是什么?谢谢。
I want to create the following functionality: I want to be able to show an image on a window, if it is provided, or a linear gradient brush if the image is not present. I came up with two approaches:
To create a
Border
and to applyImageBrush
to the borderBackground
property if
the imageUri
is provided, orLinearGradientBrush
if not. This is easy to
implement: The view model would supply the border background property either with image
brush or linear gradient brush. But there's one big problem: if the image dimensions
don't fit the border size, the image is deformed which is something I wish to avoid. Is
there a way to setImageBrush
and to preserve the image dimensions ratio, i.e. to
apply something likeStretch = Stretch.Uniform
?To create a
Border
and anImage
inside of it. Then, to create a data trigger for
the border, and if the imageUri
(a property from the view model) isnull
, to set
theBackground
of the border toLinearGradientBrush
and to leave it blank if
otherwise. I tried creating this, but the data trigger never understood thenull
case. There is also a problem with theImage
because ifnull
is provided forImageSource
property, an exception is thrown. The code looks like this:<Border Width="130" Height="170"> <Border.Style> <Style TargetType="Border"> <Style.Triggers> <DataTrigger Binding="{Binding Image}" Value="{x:Null}"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="#696969" Offset="0.0" /> <GradientStop Color="#2E2E2E" Offset="1.0" /> </LinearGradientBrush> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </Border.Style> <Image Name="image" Stretch="Uniform"> <Image.Source> <BitmapImage DecodePixelWidth="{Binding ElementName=image, Path=Width}" UriSource="{Binding Path=Image}" /> </Image.Source> </Image> </Border>
What is the best and the easiest way to implement such functionality? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ImageBrush
派生自TileBrush
类,该类具有Stretch
属性。因此,您不能使用诸如Stretch = Stretch.Uniform
之类的内容,而只能使用这样的内容。ImageBrush
is derived from theTileBrush
class, which has aStretch
property. So you can use not something likeStretch = Stretch.Uniform
, but exactly that.