App*_*Fzx 5 c# wpf imagelist winforms
我想将一个项目移动到 WPF,其中有一个ImageList(通过在设计视图中选择 25 个图像来加载),我用它来创建按钮,如下所示: 我已将项目简化为以下代码。这是我的整个项目(除了 .Designer.cs 中自动生成的代码):
public partial class Form1 : Form
{
Button[] buttonList = new Button[25];
Size buttonSize = new Size(140, 140);
public Form1()
{
InitializeComponent();
this.ClientSize = new Size(142 * 5, 142 * 5);
for (int i = 0; i < buttonImages.Images.Count; i++)
{
buttonList[i] = new Button();
buttonList[i].Size = buttonSize;
buttonList[i].Location = new Point(
(i % 5) * (buttonSize.Width + 2) + 1,
(i / 5) * (buttonSize.Height + 2) + 1);
buttonList[i].Image = buttonImages.Images[i];
}
SuspendLayout();
Controls.AddRange(buttonList);
ResumeLayout(false);
}
}
Run Code Online (Sandbox Code Playgroud)
我似乎不知道如何在 WPF 中完成这个琐碎的任务。据我所知,从这里的答案(像这样)我应该是
有人可以帮忙把它翻译成WPF吗?老实说,我不知道从哪里开始。
如果重要的话,它运行时的样子如下:

我们将为此使用 MVVM。
首先我们将制作一个模型。
public class MyModel
{
public BitmapSource Picture { get; set; }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我们的ViewModel
public class MyViewModel
{
public ObservableCollection<MyModel> Images { get; set; }
public ICommand ButtonClicked { get; set; }
... Logic to populate the images
}
Run Code Online (Sandbox Code Playgroud)
然后我们的观点
<Window x:Class="TestWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:TestWPF"
Title="MainWindow"
Height="350"
Width="525">
<Window.Resources>
<loc:MyViewModel x:Key="ViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<ListView ItemsSource="{Binding Images}">
<ListView.ItemTemplate>
<DataTemplate>
<Button Command="{Binding ButtonClicked, RelativeSource=Parent}"
CommandParameter="{Binding Description}">
<Image Width="50"
Height="50"
Source="{Binding Picture}"></Image>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
这将创建一个应该以相同方式起作用的列表。
| 归档时间: |
|
| 查看次数: |
7064 次 |
| 最近记录: |