在我的XAML页面中,我使用上下文菜单定义图像:
<Image Height="{Binding Image.Height, Mode=TwoWay}" MaxHeight="2000" HorizontalAlignment="Left" StretchDirection="Both" Stretch="Uniform"
Source="{Binding Image.ImageData, Converter={StaticResource ImageByteConverter}}"
x:Name="Image1">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="200" Click="ImageHeight200_Click" />
<MenuItem Header="400" Click="ImageHeight400_Click" />
<MenuItem Header="600" Click="ImageHeight600_Click" />
<MenuItem Header="800" Click="ImageHeight800_Click" />
<MenuItem Header="1000" Click="ImageHeight1000_Click" />
</ContextMenu>
</Image.ContextMenu>
</Image>
现在我想添加代码来调整图像大小。
当我写这样的东西时
private void ImageHeight200_Click(object sender, RoutedEventArgs e)
{
var img = (Image)e.Source;
img.Height = 200;
}
它访问MenuItem但不访问图像,我收到一条错误消息:
“System.Windows.Controls.MenuItem”类型的对象无法转换为“System.Windows.Controls.Image”类型。
我的问题是:
如何访问图像对象?
答案 0 :(得分:0)
您只需按名称引用图片
即可private void ImageHeight200_Click(object sender, RoutedEventArgs e)
{
Image1.Height = 200;
}
答案 1 :(得分:0)
您可以使用ContextMenu的PlacementTarget属性
private void ImageHeight200_Click(object sender, System.Windows.RoutedEventArgs e){
MenuItem mnu = sender as MenuItem;
Image sp = null;
if(mnu!=null)
{
sp = ((ContextMenu)mnu.Parent).PlacementTarget as Image;
}}