Applying transforms from DataTemplates in WPF

2019-08-30 04:09发布

I've created a DataTemplate for my objects in a ResourceDictionary file. The template is basically an image that is loaded from the disk. Now, what happens is that I want to align the image to a specific point on my Canvas but not by its upper left point but its center point, that's why I want to apply a translate transform for X = -Width / 2 and Y = -Height / 2 but I don't know how to apply them via the DataTemplate.

Any help will be appreciated, thanks!

2条回答
Lonely孤独者°
2楼-- · 2019-08-30 05:07

you can take the advantage of using loaded event on the data template child Example:

if you are using grid as data template content

<DataTemplate>
 <Grid Loaded="Grid_Loaded">
   <Image></Image>
 </Grid>
</DataTemplate>

you can write the transformation code in the .cs file using sender object.

查看更多
The star\"
3楼-- · 2019-08-30 05:15

Try using databinding on Canvas' the AttachedProperties and an IValueConverter to transform the offsets to whatever you want.

For instance:

class ImageToCanvasConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return -(int)value / 2;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Two-way binding not supported
        throw new InvalidOperationException(); 
    }
}

<Grid.Resources>
    <myAssembly:ImageToCanvasConverter x:Key="imageToCanvasConverter" />
    <DataTemplate ...>
        <Image Canvas.Left="{Binding Path=Width, Converter={StaticResource imageToCanvasConverter}, Mode=OneTime}"
               Canvas.Top="{Binding Path=Height, Converter={StaticResource imageToCanvasConverter}, Mode=OneTime}"
               ... />
    </DataTemplate>
</Grid.Resources>
查看更多
登录 后发表回答