Reputation: 783
Inside my window 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>
(I added to window resources this converter)
I would like to add background image with blur effect to this grid (with MVVM pattern) but my property never called in my viewmodel. If i use just converter with "Path=." the converter going to work but I have to use static ImageSource in conveter because if i add any object type for ImageSource (to path) (BitmapImage,ImageSource,..,etc), the converter will not call. (I tried to use UpdateSourceTrigger with PropertyChanged value but this solution didn't help to me.) The converter just an unwanted solution because this is the only one way to set my background correctly because my ImageSouce property has wanted value but its not works without converter and unfortunately the converter will not work too if i add any path to binding.
Here is my property inside the ViewModel:
private ImageSource _imageSource;
public ImageSource ImageSource
{
get
{
return _imageSource;
}
set
{
_imageSource = value;
OnPropertyChanged();
}
}
Any idea to set my background image with Blur effect correctly with MVVM pattern and without use uri path? (i dont want to save the image to physical storage)
Upvotes: 1
Views: 1417
Reputation: 169390
A VisualBrush
is not part of the element tree so it doesn't inherit the DataContext
of the Grid
.
But you could define the Image
as a resource and bind its Source
property to a property of the parent window using an {x:Reference}
. This should work:
<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>
Upvotes: 1