我想通过添加第二个来源来扩展 Image 类。我想在 XAML 中定义第二个源(如原始源)并在鼠标进入/离开此图像时更改这些图像。
我试过自己:
class MainMenuImageButton : Image
{
public static readonly DependencyProperty Source2Property;
public ImageSource Source2
{
get { return Source2; }
set
{
this.MouseEnter+=new System.Windows.Input.MouseEventHandler(MainMenuImageButton_MouseEnter);
}
}
public void MainMenuImageButton_MouseEnter(object sender, MouseEventArgs e)
{
this.Source = Source2;
}
}
但它不起作用,我认为我做错了。有人可以帮忙吗?
[更新]
我写了这个:
class MainMenuImageButton : Image
{
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
var source = (BitmapSource)Source;
var x = (int)(hitTestParameters.HitPoint.X / ActualWidth * source.PixelWidth);
var y = (int)(hitTestParameters.HitPoint.Y / ActualHeight * source.PixelHeight);
var pixels = new byte[4];
source.CopyPixels(new Int32Rect(x, y, 1, 1), pixels, 4, 0);
if (pixels[3] < 10) return null;
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
public ImageSource Source1
{
get { return GetValue(ImageSourceProperty) as ImageSource; }
set { base.SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("Source1", typeof(ImageSource), typeof(MainMenuImageButton));
public ImageSource Source2
{
get { return GetValue(ImageSource2Property) as ImageSource; }
set { base.SetValue(ImageSource2Property, value); }
}
public static readonly DependencyProperty ImageSource2Property = DependencyProperty.Register("Source2", typeof(ImageSource), typeof(MainMenuImageButton));
public MainMenuImageButton() : base()
{
this.MouseEnter += new MouseEventHandler(MainMenuImageButton_MouseEnter);
this.MouseLeave += new MouseEventHandler(MainMenuImageButton_MouseLeave);
}
void MainMenuImageButton_MouseLeave(object sender, MouseEventArgs e)
{
this.Source = this.Source1;
}
void MainMenuImageButton_MouseEnter(object sender, MouseEventArgs e)
{
this.Source = this.Source2;
}
}
但有时它可以工作,有时会出现异常:“PresentationCore.dll 中发生了类型为 'System.ArgumentException' 的未处理异常
附加信息:该值超出预期范围。”
我不确定我是否理解,但我试过这个:
class MainMenuImageButton : Image
{
public static readonly DependencyProperty Source2Property = DependencyProperty.Register("Source2", typeof(ImageSource), typeof(MainMenuImageButton), new PropertyMetadata(true));
public ImageSource Source2
{
get { return (ImageSource)GetValue(Source2Property); }
set
{
BitmapImage logo = new BitmapImage(new Uri(value.ToString(), UriKind.Relative));
SetValue(Source2Property, logo);
this.MouseEnter+=new System.Windows.Input.MouseEventHandler(MainMenuImageButton_MouseEnter);
}
}
public void MainMenuImageButton_MouseEnter(object sender, MouseEventArgs e)
{
this.Source = Source2;
}
}
仍然一无所有。我在做什么错?