【发布时间】:2020-01-21 09:21:04
【问题描述】:
我正在构建一个应用程序,它将在 2D 网格中显示按钮列表,类似于 How to populate a WPF grid based on a 2-dimensional array
挑战在于判断在buttonClick 事件处理程序中单击了哪个按钮(以 i、j 表示)。
我最初的想法是让按钮名称包含 i,j 的字符串表示形式(例如 'button_2_3'),但无法使用 '{binding ...}' 指定名称。
不能使用按钮标签(button.content),因为应用程序要求在按钮上显示非唯一标签(按钮标签代表单元格上的一块,类似于国际象棋,其中“Q”标签表示皇后的位置)。
最好的选择似乎是在按钮的 CommandParameter 属性中存储行/列的表示。
我的问题:如何填充每个按钮的 CommandParameter 以便于提取单击按钮的 (i, j) ?将用户定义的数据附加到按钮是否有更好的选择?
发件人:How to populate a WPF grid based on a 2-dimensional array
<Window.Resources>
<DataTemplate x:Key="DataTemplate_Level2">
<Button Content="{Binding}" Height="40" Width="50" Margin="4,4,4,4" click="buttonClick"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplate_Level1">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
和
public Window1()
{
List<List<int>> lsts = new List<List<int>>();
for (int i = 0; i < 5; i++)
{
lsts.Add(new List<int>());
for (int j = 0; j < 5; j++)
{
lsts[i].Add(i * 10 + j);
}
}
InitializeComponent();
lst.ItemsSource = lsts;
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
【问题讨论】:
-
有没有更好的替代方法将用户定义的数据附加到按钮上?使用标签。
-
UniformGrid 将是 ItemsPanel(具有一维 ItemsSource)的更好选择。查看示例:stackoverflow.com/q/43097851/1506454、stackoverflow.com/q/37145391/1506454
-
最终合并了两个提议的解决方案 - 使用“标签”来存储具有“行”和“列”以及“值”属性的对象。
标签: wpf button datatemplate commandparameter