WPF图像作为工具提示 - DPI问题

时间:2016-11-03 09:37:13

标签: c# wpf

我一直在摸不着头脑。

在我的MainWindow上我有一个图像谁的工具提示应该弹出图像的实际大小(或者高度不大于MainWindow本身):

<Image x:Name="ss1" Grid.Column="0" Grid.Row="0" Margin="0">
    <Image.ToolTip>
        <ToolTip DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
            <Border BorderBrush="Black" BorderThickness="1" Margin="5,7,5,5">
                <Image Source="{Binding Source}" MaxHeight="{Binding ElementName=MW,Path=Height}" Stretch="Uniform" ToolTipService.Placement="Top"/>
            </Border>
        </ToolTip>
    </Image.ToolTip>
</Image>

(MainWindow的x:名称为'MW')

在其他地方我正在将BitmapImage加载到此图像控件中:

Image img = (Image)mw.FindName("ss1");
img.Source = GetBitmapImageFromDisk(path, UriKind.Absolute);

GetBitMapImageFromDisk方法:

public static BitmapImage GetBitmapImageFromDisk(string path, UriKind urikind)
{
    if (!File.Exists(path))
        return null;
    try
    {
        BitmapImage b = new BitmapImage(new Uri(path, urikind));
        return b;
    }
    catch (System.NotSupportedException ex)
    {       
        BitmapImage c = new BitmapImage();
        return c;
    }        
}

图像工具提示会在鼠标悬停时弹出,但问题是图像的大小似乎取决于图像本身的DPI。因此,如果出于某种原因它将目标指向DPI的图像是'762',那么ToolTip图像在显示时会非常小。

有人可以建议使用我当前的代码来减轻这种情况吗?在运行时加载的图像几乎可以是任何大小,DPI和宽高比。

1 个答案:

答案 0 :(得分:0)

非常感谢Clemens的链接,它确实非常有用(特别是pixelwidth和pixelheight属性)。

我在xaml中定义最大值时遇到了一些问题,所以最后我把逻辑抽象到后面的代码中。

完整性代码:

<强> XAML:

<Image x:Name="ss1" Grid.Column="0" Grid.Row="0" Margin="0">
    <Image.ToolTip>
        <ToolTip DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
            <Border BorderBrush="Black" BorderThickness="1" Margin="5,7,5,5">
                <Image Source="{Binding Source}" Stretch="Uniform" ToolTipService.Placement="Top"/>
            </Border>
        </ToolTip>
    </Image.ToolTip>
</Image>

其他类:

Image img = (Image)mw.FindName("ss1");
SetImage(img, path, UriKind.Absolute);

方式:

public static void SetImage(Image img, string path, UriKind urikind)
{            
    if (!File.Exists(path))
        return;
    try
    {
        // load content into the image
        BitmapImage b = new BitmapImage(new Uri(path, urikind));
        img.Source = b;

        // get actual pixel dimensions of image
        double pixelWidth = (img.Source as BitmapSource).PixelWidth;
        double pixelHeight = (img.Source as BitmapSource).PixelHeight;

        // get dimensions of main window
        MainWindow mw = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
        double windowWidth = mw.ActualWidth;
        double windowHeight = mw.ActualHeight;

        // set max dimensions on Image.ToolTip
        ToolTip tt = (ToolTip)img.ToolTip;
        tt.MaxHeight = windowHeight / 1.1;
        tt.MaxWidth = windowWidth / 1.1;
        img.ToolTip = tt;
    }

    catch (System.NotSupportedException ex)
    {
        img.Source = new BitmapImage();
    }
}

一旦我能识别像素宽度&amp;图像的高度在ToolTip本身设置MaxHeight和MaxWidth相当简单。