Applying transforms from DataTemplates in WPF

泄露秘密 提交于 2019-12-25 14:12:49

问题


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!


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/8588869/applying-transforms-from-datatemplates-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!