我一直在摸不着头脑.
在我的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);
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图像在显示时会非常小.
解决方法
非常感谢Clemens的链接,它确实非常有用(特别是pixelwidth和pixelheight属性).
我在xaml中定义最大值时遇到了一些问题,所以最后我将逻辑抽象到后面的代码中.
完整性代码:
XAML:
<Image x:Name="ss1" Grid.Column="0" Grid.Row="0" Margin="0"> <Image.ToolTip> <ToolTip DataContext="{Binding PlacementTarget,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(); } }
一旦我能识别像素宽度&图像的高度在ToolTip本身上设置MaxHeight和MaxWidth相当简单.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。