开发者

How to correctly bind two classes in C#

开发者 https://www.devze.com 2023-03-04 15:53 出处:网络
I want something like this Class1 { DateTime time } Class2 { List<Class1> } Class3 : ObservableCollection<Class开发者_StackOverflow社区2> { }

I want something like this

Class1 { DateTime time }
Class2 { List<Class1> }
Class3 : ObservableCollection<Class开发者_StackOverflow社区2> { }

but I implemented this:

Class1 { DateTime time }
Class2 { List<DateTime> }
Class3 : ObservableCollection<Class2> { }

with the thought that it saves more memory. Each object's time attribute is unique. I know both solutions are wrong so, what is the correct way of binding these two objects? Can I access Class1's attributes through Class3?

EDIT: The above isn't the actual code, is just to explain my problem. The classes have other attributes and Class1 and Class2 are used elsewhere too


In your second solution, there's no way of getting to any instance of Class1 from Class3 with what you've shown us - you could have a load of Class3 and Class2 instances, but never create an instance of Class1 at all.

If your first solution represents what you logically want, why not use it?

On the other hand, if your Class1 code doesn't have any state apart from a DateTime, do you need it to exist at all?


First, what problem are you trying to solve? Saving memory isn't the problem I see here. Are there millions of these objects being created that force you into this solution?

If not, please consider the most readable / maintainable solution possible. Otherwise feel free to place share your problem to place it in context for us. So we can take a closer look and provide a better answer.


If you are using Class1 in other places, meaning the objects already exists, then using them in a List will not need a lot of memory. It will only store a pointer to the object (4/8 Bytes) instead of a copy of it. In fact it may need more memory using the List of DateTime.

So Memory shouldn't be a problem like others pointed out.

As to visibility from Binding. If you include a publicy accesible property for the object you will be able to see it.

If your collection of Class1 object can change however, you should consider implementing ObservableCollection also, to tell WPF when the collection changes.

0

精彩评论

暂无评论...
验证码 换一张
取 消