WPF中动态创建控件,并给最后创建控件加入事件

//容器名字TestCanvas.
//Btn_Click 事件
private void SetControlsToCanvas(int Num)
{
if (Num<=1)
{
t2.KeyDown += Btn_Click;
return;
}
for (int i = 1; i < Num; i++)
{
if (i==Num-1)
{
TheWay_GentrateControls(i,true);
TextBox TLast =TestCanvas.FindName(“LastCon”) as TextBox;
TLast.KeyDown += Btn_Click;
}
else
{
TheWay_GentrateControls(i);
}

        }
    }

    private void TheWay_GentrateControls(int Num,bool LastControl=false)
    {
        double ModelOfControlsLeft = Canvas.GetLeft(t1);
        double ModelOfControlsTop = Canvas.GetTop(t1);
        double _ModelOfControlsLeft = Canvas.GetLeft(t2);
        double _ModelOfControlsTop = Canvas.GetTop(t2);
        double ModelOfControlsLeft_Label = Canvas.GetLeft(Lab1);
        double ModelOfControlsTop_Label = Canvas.GetTop(Lab1);
        double _ModelOfControlsLeft_Label = Canvas.GetLeft(Lab2);
        double _ModelOfControlsTop_Label = Canvas.GetTop(Lab2);
        string XamlLabelCopy = XamlWriter.Save(Lab1);
        Label GenreateLabel = XamlReader.Parse(XamlLabelCopy) as Label;
        Canvas.SetLeft(GenreateLabel, ModelOfControlsLeft_Label);
        Canvas.SetTop(GenreateLabel, (_ModelOfControlsTop_Label-ModelOfControlsTop_Label)*Num + _ModelOfControlsTop_Label);
        TestCanvas.Children.Add(GenreateLabel);
        GenreateLabel.Content = "绑定码" + Num;
        string XamlTextBox = XamlWriter.Save(t1);
        TextBox T4 = XamlReader.Parse(XamlTextBox) as TextBox;

        Canvas.SetLeft(T4, ModelOfControlsLeft);
        Canvas.SetTop(T4, (_ModelOfControlsTop - ModelOfControlsTop) *Num+_ModelOfControlsTop);
        TestCanvas.Children.Add(T4);
        if (LastControl)
        {
            T4.Name = "LastCon";
            TestCanvas.RegisterName("LastCon", T4);
        }
    }

你可能感兴趣的:(wpf)