在WPF中从DataTemplates应用转换 [英] Applying transforms from DataTemplates in WPF

查看:76
本文介绍了在WPF中从DataTemplates应用转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 ResourceDictionary 文件中为对象创建了一个DataTemplate。模板基本上是从磁盘加载的映像。现在,发生的事情是我想将图像与Canvas上的特定点对齐,而不是按左上角而是中心点对齐,这就是为什么我要对 X =-应用转换变换的原因宽度/ 2
Y =-高度/ 2 ,但我不知道如何通过DataTemplate应用它们。

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.

任何帮助将不胜感激!

推荐答案

尝试在画布的AttachedProperties和 IValueConverter 进行转换所需偏移量。

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

例如:

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>

这篇关于在WPF中从DataTemplates应用转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆