开发者

Passing large sets of data into user controls

开发者 https://www.devze.com 2023-02-01 07:05 出处:网络
Since UserControls in WPF have to have parameterless constructors, what is the correct way for supplying them with fairly complex data that is needed \"near\" the time of construction. I have tried us

Since UserControls in WPF have to have parameterless constructors, what is the correct way for supplying them with fairly complex data that is needed "near" the time of construction. I have tried using dependency properties for this, but am running into issues with the Visual Studio designer balking at attempts to pass stuff like a Dictionary<string,MyObject> into an IDictionary<string,MyObject> typed dependency property. At some point it must want an exact compile time type match, or the XAML doesn't come up in the designer, although the application executes just fine.

Basically, I want a good way to pass in stuff that I would normally pass into a constructor into a User Control. What's the best way?

Update: The user control in question will always be created from XAML,开发者_如何学编程 so having a non-parameterless construction in addition to the parameterless one is not an option.

Update 2: An interesting idea would be to have something accessible from the parameterless constructor that I can get my initialization data from. Something like perhaps asking the question: Which of my already initialized ancestors implements an IMyDataProvider interface? This could be similar to how the relative source to ancestor type bindings work, except done programatically from the user control constructor.


If the only problem you are having is passing in derived types, you can pass in instead a simple concrete container class containing your complex types as properties. For example:

public class InitializationData
{
    public IDictionary<TKey, TValue> Dictionary { get; set; }
}

This level of indirection will overcome the limitations of the Visual Studio designer.


A couple of options.

1, You can have more than one constructor, a parameterless one for when your control is created via XAML and another that takes a set of parameters for when you create it directly via code. If you definitely don't want to create your instance via code then...

2, Add a public property that only has a setter and is defined with the exact dictionary type you want to pass in and use as the data for initializing the control. The property only needs to be called once. You can have other properties that are getters/setters that expose that initialized data in order more generic types.

0

精彩评论

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