[英]C# WPF MenuItem with image as background programmatically
我对 XAML 很不满意,但我只需要创建一个菜单项,它有一个图像而不是文本。
我已经让它以某种方式工作,图像被呈现并从资源中加载,但是在鼠标悬停时图像正在消失。
你能帮我以编程方式完成这项工作吗? 在互联网上,我只找到 XAML 示例,但没有以编程方式。
提前致谢。
var addOnFrameworkMenuItem = new MenuItem();
var image = new Image();
Assembly asm = Assembly.GetExecutingAssembly();
System.IO.Stream imageStream = asm.GetManifestResourceStream("MyProject.Ressources.image.png");
BitmapFrame bmp = BitmapFrame.Create(imageStream);
image.Source = bmp;
ImageBrush ib = new ImageBrush();
ib.ImageSource = bmp;
addOnFrameworkMenuItem.Width = 150;
addOnFrameworkMenuItem.Height = 31;
addOnFrameworkMenuItem.Background = ib;
谢谢你,吉姆,
你的提示帮助了我。 对于我的图像消失问题,我只需要将图像放入 header:
addOnFrameworkMenuItem.Header = 图像;
此外,我发现可以通过以下方式设置大部分样式属性:
// Create a style to apply to the button
Style s = new Style();
s.TargetType = typeof(System.Windows.Controls.MenuItem);
s.Setters.Add(new Setter(System.Windows.Controls.MenuItem.FontSizeProperty, 11.0));
s.Setters.Add(new Setter(System.Windows.Controls.MenuItem.BackgroundProperty, Brushes.Orange));
s.Setters.Add(new Setter(System.Windows.Controls.MenuItem.ForegroundProperty, Brushes.Black));
s.Setters.Add(new Setter(System.Windows.Controls.MenuItem.FontFamilyProperty, new FontFamily("Arial")));
s.Setters.Add(new Setter(System.Windows.Controls.MenuItem.FontWeightProperty,FontWeights.Bold));
Trigger t2 = new Trigger();
t2.Property = System.Windows.Controls.MenuItem.IsMouseOverProperty;
t2.Value = true;
t2.Setters.Add(new Setter(Control.BackgroundProperty, System.Windows.Media.Brushes.Violet));
s.Triggers.Add(t2);
addOnFrameworkMenuItem.Style = s;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.