源背景图像数据绑定不起作用



在我的窗口内xaml:

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.Style>
<Style TargetType="{x:Type Grid}">
<Setter Property="Background">
<Setter.Value>
<VisualBrush>
<VisualBrush.Visual>
<Image Source="{Binding Path=ImageSource,Converter={StaticResource imgconverter}}">
<Image.BitmapEffect>
<BlurBitmapEffect KernelType="Box" />
</Image.BitmapEffect>
</Image>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</Style>
</Grid.Style>
</Grid>

(我将此转换器添加到窗口资源)

我想将具有模糊效果的背景图像添加到此网格(使用 MVVM 模式),但我的属性从未在我的视图模型中调用过。如果我只使用带有"Path=."的转换器,转换器将起作用,但我必须在 conveter 中使用静态 ImageSource,因为如果我为 ImageSource(到路径)(BitmapImage,ImageSource,..,等)添加任何对象类型,转换器将不会调用。(我尝试将UpdateSourceTrigger与PropertyChanged值一起使用,但此解决方案对我没有帮助。转换器只是一个不需要的解决方案,因为这是正确设置背景的唯一一种方法,因为我的 ImageSouce 属性想要值,但没有转换器就不起作用,不幸的是,如果我添加任何绑定路径,转换器也无法工作。

这是我在视图模型中的属性:

private ImageSource _imageSource;
public ImageSource ImageSource
{
get
{
return _imageSource;
}
set
{
_imageSource = value;
OnPropertyChanged();
}
}

有什么想法使用 MVVM 模式正确设置具有模糊效果且不使用 uri 路径的背景图像吗?(我不想将图像保存到物理存储)

VisualBrush

不是元素树的一部分,因此它不会继承GridDataContext

但是,您可以将Image定义为资源,并使用{x:Reference}将其Source属性绑定到父窗口的属性。这应该有效:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300" x:Name="win">
<Window.Resources>
<local:imgconverter x:Key="imgconverter" />
</Window.Resources>
<Grid>
<Grid.Resources>
<Image x:Key="img" Source="{Binding Path=DataContext.ImageSource,Converter={StaticResource imgconverter}, Source={x:Reference win}}">
<Image.BitmapEffect>
<BlurBitmapEffect KernelType="Box" />
</Image.BitmapEffect>
</Image>
</Grid.Resources>
<Grid.Style>
<Style TargetType="{x:Type Grid}">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Visual="{StaticResource img}" />
</Setter.Value>
</Setter>
</Style>
</Grid.Style>
<TextBlock Text="..." />
</Grid>
</Window>

最新更新