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

本文关键字:DPI 问题 工具提示 图像 WPF | 更新日期: 2023-09-27 18:16:18

这个问题我已经挠头好一阵了。

在我的主窗口上,我有一个图像,它的工具提示应该弹出图像的实际大小(或高度不大于主窗口本身):

<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's x:name is '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'工具提示图像在显示时真的很小

谁能建议一种方法来减轻我目前的代码?在运行时加载的图像几乎可以是任何大小、DPI和宽高比。

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

非常感谢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>

Other Class:

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();
    }
}

一旦我可以确定像素宽度&在工具提示上设置MaxHeight和MaxWidth是相当简单的。