且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在WPF窗口中使用Generics参数

更新时间:2023-12-03 15:30:10

您正在混淆方法参数和通用参数。阅读两者,了解它们的工作原理。您的 InitializeComponent 是自动生成的代码,由您的XAML生成。它被设计用于从类 Window 派生的类,并且构造函数应该没有参数。



原则上,这样的构造函数可以工作(你没有解释为什么它不起作用,这取决于你如何使用它),但我怀疑它是否有意义。



此类代码不适用于泛型类。您应该重新设计代码。但是如果你想使用泛型,你需要正确地学习它们。看了你的代码后,我怀疑你有线索。



如果你想得到一些明确的建议,你需要解释你的最终目标。



-SA


至#1:

我现在喜欢这样:

  public   partial   class 选择< T1,T2> :Window 
其中 T1:UserControl, new ()
其中 T2:实体, new ()
{
public 选择(T1 usercontrol,List< T2> list, bool canChooseAll)
{
InitializeComponent();
}
}





这样做,我必须编辑Choosen.gics来改变类的名称选择到选择< T1,T2>,但是当我编译它时,Choosen.gics文件将被设置为默认值,并引发错误:找不到 InitializeComponent


How the Windows' constructor can accept 2 Generics parameter?
Such like this:

Choosen is a Window;
CustomerControl、UsersControl、StyleControl are UserControls;
CutomerInfo、UsersInfo、StyleInfo are classes;

CustomerControl cc = new CustomerControl();
List<CutomerInfo> lci = new List<CutomerInfo>(10);

UsersControl uc = new UsersControl();
List<UsersInfo> lui = new List<UsersInfo>(20);

StyleControl sc = new StyleControl();
List<StyleInfo> lsi = new List<StyleInfo>(30);

Choosen chooseCustomer = new Choosen(cc,lci);chooseCustomer.Show();
Choosen chooseUsers = new Choosen(uc,lui);chooseUsers.Show();
Choosen chooseStyle = new Choosen(sc,lsi);chooseStyle.Show();



I tried like this,but the Window doesn't work;

public partial class Choosen<T1, T2> : Window
{
    public Choosen(T1 uc, List<T2> list)
    {
        InitializeComponent();  //it can't initialize now;
    }
}

You are confusing method parameters and generic parameters. Read about both, to see how they work. Your InitializeComponent is the auto-generated code, generated from your XAML. It is designed to work with classes derived from the class Window, and the constructor should have no parameters.

In principal, such constructor can work (you did not explain why "it does not work", it depends on how you use it), but I doubt it makes any sense.

And such code is not designed to work with generic classes. You should rather redesign your code. But if you want to use generics, you need to learn them properly. After looking at your code, I doubt you have a clue.

If you want to get some definitive advice, you need to explain your ultimate goal.

—SA


To #1:
I do like this now:
public partial class Choosen<T1, T2> : Window
       where T1 : UserControl, new()
       where T2 : Entities, new()
{
public Choosen(T1 usercontrol, List<T2> list, bool canChooseAll)
       {
           InitializeComponent();
       }
}



to do like this ,I have to edit the Choosen.g.i.cs to change the class's name "Choosen" to "Choosen<T1, T2>",but when i compile it ,the Choosen.g.i.cs file will be set to default,and raise an error:"Can't find InitializeComponent"