Reputation: 181
I have a simple grid that displays a portion of an image.
<Grid x:Name="back_side" Margin="-1" RenderTransformOrigin="0.5,0.5" RenderTransform="{Binding ScaleTransformBack}" Width="Auto">
<Image Source="/NameSpace;component/Resources/image.jpg" Stretch="Fill">
<Image.Clip>
<RectangleGeometry Rect="{Binding RectGeo}"/>
</Image.Clip>
</Image>
</Grid>
I have tried binding directly to a RectangleGeometry in code behind as well. The clip doesn't seem to want to work. Any suggestions? Anyone have any experience with binding a clip to an image?
I need to be able to programmatically segment a specific image across a number of controls. Using the clip as the calculated portion for each control to display.
Upvotes: 0
Views: 1544
Reputation: 33364
If you want to display only part of your image you can use CroppedBitmap
as Image.Source
<Image>
<Image.Source>
<CroppedBitmap Source="/NameSpace;component/Resources/image.jpg" SourceRect="{Binding RectGeo}"/>
</Image.Source>
</Image>
You can bind CroppedBitmap.SourceRect
but you need to make sure that RectGeo
is of a Int32Rect
type
EDIT
Unfortunately if you plan to change SourceRect
at runtime this won't work as:
After initialization, property changes are ignored
So what you can do is create custom IValueConverter
which will create a CroppedBitmap
:
public class CropBitmapConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new CroppedBitmap(new BitmapImage(new Uri((string)parameter, UriKind.RelativeOrAbsolute)), (Int32Rect)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
and use it with your binding:
<Image ... Source="{Binding Path=RectGeo, Converter={StaticResource CropBitmapConverter}, ConverterParameter='pack://application:,,,/NameSpace;component/Resources/image.jpg'}" />
Upvotes: 5