如何在工具提示中获取图像属性

How to get image properties in tooltip

我有一项任务是在工具提示中获取图像类型、尺寸和大小。我试过使用这段代码。我得到了图片 url,无法在工具提示中获取图片 属性..

 <Image Source="{Binding Path=UriSource}" Stretch="Fill" Width="100" Height="120">
    <Image.ToolTip>
         <ToolTip Content="{Binding}"/>
    </Image.ToolTip>
</Image>

如何在工具提示 WPF 中获取图像尺寸?

如果要获取父控件的属性,必须设置ToolTipDataContext:

    <Image Source="face-monkey.png" Width="60">
        <Image.ToolTip>
            <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
                <StackPanel Orientation="Horizontal">
                    <Label Content="Width:" FontWeight="Bold"/>
                    <Label Content="{Binding Width}"/>
                </StackPanel>
            </ToolTip>
        </Image.ToolTip>
    </Image>

由于您的绑定源对象似乎是一个 BitmapSource,您可以直接绑定到它的属性,例如它的 PixelWidth 和 PixelHeight:

<Image Source="{Binding}" Width="100" Height="120">
    <Image.ToolTip>
        <ToolTip Content="{Binding}">
            <ToolTip.ContentTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding PixelWidth, StringFormat=Width: {0}}"/>
                        <TextBlock Text="{Binding PixelHeight, StringFormat=Height: {0}}"/>
                    </StackPanel>
                </DataTemplate>
            </ToolTip.ContentTemplate>
        </ToolTip>
    </Image.ToolTip>
</Image>

或更短:

<Image Source="{Binding}" Width="100" Height="120">
    <Image.ToolTip>
        <StackPanel>
            <TextBlock Text="{Binding PixelWidth, StringFormat=Width: {0}}"/>
            <TextBlock Text="{Binding PixelHeight, StringFormat=Height: {0}}"/>
        </StackPanel>
    </Image.ToolTip>
</Image>

如果绑定源不是 BitmapSource,而只是图像文件 Uri 或路径字符串,您可以绑定到图像 Source [=21] 中的(自动创建的)BitmapSource 对象=] 像这样:

<Image Source="{Binding}" Width="160" Height="120">
    <Image.ToolTip>
        <ToolTip DataContext="{Binding PlacementTarget.Source,
                                       RelativeSource={RelativeSource Self}}">
            <StackPanel>
                <TextBlock Text="{Binding PixelWidth, StringFormat=Width: {0}}"/>
                <TextBlock Text="{Binding PixelHeight, StringFormat=Height: {0}}"/>
            </StackPanel>
        </ToolTip>
    </Image.ToolTip>
</Image>