【问题标题】:Dynamically created button in WPFWPF中动态创建的按钮
【发布时间】:2012-02-15 21:04:13
【问题描述】:

我正在尝试做一些 WPF,直到现在才真正完成了 windows 窗体,而不是很多......

我要做的只是在代码(不是 xaml)中动态设置按钮以显示图像并将按钮的大小设置为自动调整图像大小。

下面的代码会加载图像,但是当鼠标悬停在按钮上并且按钮不会自动调整图像大小时,它会加载。

tbButtonPicture 包含 PC 上到位图的本地路径,例如C:\temp\my Artwork\test1.bmp

这就是我目前所拥有的,它位于一个循环中:

Console.WriteLine(tbButtonPicture);
System.Windows.Controls.Button newBtn = new Button();
//newBtn.Content = i.ToString();
newBtn.Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture)));
newBtn.Name = "Button" + i.ToString();
sp.Children.Add(newBtn);

i++;

【问题讨论】:

  • 抱歉 Nemesv,我已经更新了一个问题!
  • 为什么不添加一些ItemsControl 派生类并将其绑定到数据容器?
  • 嗨,Serge,谢谢你的建议,但我不知道该怎么做!我将谷歌 ItemsControl。当你在 winforms 中设置一个属性时会更容易:( 我认为即使是这个简单的任务也给了我很多新的东西来学习......
  • 阅读the overviews,尤其是data binding和data templating上的那些。

标签: c# wpf button


【解决方案1】:

将您的图像包装在 Image 控件中并将其设置为按钮内容,您应该会获得所需的效果。

  System.Windows.Controls.Button newBtn = new Button();
  Image imageControl = new Image();
  imageControl.Source = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture));
  newBtn.Content = imageControl;
  newBtn.Name = "Button" + i.ToString();
  sp.Children.Add(newBtn);

  i++;

但我完全同意上述 cmets: 尝试在 xaml 中解决您的问题更容易。阅读建议的资源,它们真的很有帮助。

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多