关于你的第一个问题:
要处理这个问题,您应该引入一个字典,其中按钮是键,您的值是客户机。因此,您可以在ClickHandler中获取链接的客户端。
public Dictionary<Button, object> clientDict = new Dictionary<Button, object>();
注意
在AddButton例程中添加按钮。再说一次:我不知道你从哪里得到你的客户,所以我增加了价值
null
. 更改此项以满足您的要求。然后添加另一个ClickHandler并获取链接的客户端:
b.Click += HandleButtonClick;
clientDict.Add(b, null);
private void HandleButtonClick(object sender, RoutedEventArgs e)
{
//Execute whatever you want from your client:
var client = clientDict[sender as Button];
}
关于你的第二个问题:
您需要添加一个RemoveMethod,从中可以得到按钮的列和行,应该将其删除。之后,您可以操作列和行属性的所有其他按钮。为了避免新添加的按钮与其他按钮不对齐,您需要更改添加过程,使新按钮的位置取决于词典中的元素数。下面是完整代码的示例:
public int buttonCounter = 1;
public Dictionary<Button, object> clientDict = new Dictionary<Button, object>();
private void RemoveBtn(Button button)
{
var row = Grid.GetRow(button);
var column = Grid.GetColumn(button);
//Rearange
foreach (var btn in clientDict.Keys)
{
var r = Grid.GetRow(btn);
var c = Grid.GetColumn(btn);
if (c > column || (c == column && r > row))
{
if (r != 0)
{
//Set the row new
Grid.SetRow(btn, r - 1);
}
else
{
//Need to set it to a new column
Grid.SetRow(btn, 3);
Grid.SetColumn(btn, c - 1);
}
}
}
myGrid.Children.Remove(button);
clientDict.Remove(button);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Create the button
Button b = new Button();
b.Height = 30;
b.Width = 100;
b.VerticalAlignment = VerticalAlignment.Top;
b.HorizontalAlignment = HorizontalAlignment.Left;
b.Margin = new Thickness(20, 20, 0, 0);
b.Content = "Button " + buttonCounter;
b.Click += HandleButtonClick;
clientDict.Add(b, null);
//Calculate the place of the button
int column = (int)(clientDict.Count / 4);
int row = clientDict.Count % 4;
//Check if you need to add a columns
if (row == 0 && myGrid.ColumnDefinitions.Count <= column)
{
ColumnDefinition col = new ColumnDefinition();
col.Width = new GridLength(column, GridUnitType.Auto);
myGrid.ColumnDefinitions.Add(col);
}
//Add the button
myGrid.Children.Add(b);
Grid.SetColumn(b, column);
Grid.SetRow(b, row);
buttonCounter++;
}
private void HandleButtonClick(object sender, RoutedEventArgs e)
{
//Execute whatever you want from you handler:
var client = clientDict[sender as Button];
}
注: