Reputation: 5808
I have an application that can display items in two different ways, in rows using a StackPanel or icons using a WrapPanel. Which way it displays these items depends on a config setting. To populate these panels I have two seperate classes one inherits from the WrapPanel the other from the StackPanel. I was able to cut down on duplicated code using an Inferface. However I still had a lot of duplicated code the only difference between the code is the references to StackPanel or WrapPanel.
What I would really like to do is create a class that inherits from either the StackPanel or WrapPanel depending on the config setting.
public class ContainerBase : <wrap or stack>
{
//Do stuff!
}
Is this possible? Am I approaching this incorrectly?
Upvotes: 2
Views: 187
Reputation: 3066
In WPF you are intended to not use controls to populate itself. Instead, use MVVM pattern.
You can achieve your goal with only one class providing the data (tipically an ObservableCollection) and loading that "view mode variable" into a property at MVVM.
Then you can use a an ItemsPanel with an DataTemplateSelector to select the view.
Upvotes: 1
Reputation: 4577
When I said "composition but not inheritance" in first comment, I meant smth like the following:
public class PanelPresentatinLogic
{
public Panel Panel{get;set;}
public void DoSomeDuplicatingStuff()
{
//Do stuff! with Panel
}
}
public class SortOfStackPanel : StackPanel
{
private readonly PanelPresentatinLogic _panelPresentatinLogic;
public SortOfStackPanel(PanelPresentatinLogic presentationLogic)
{
_panelPresentatinLogic = presentationLogic;
_panelPresentatinLogic.Panel = this;
}
public void DoSomeDuplicatingStuff()
{
_panelPresentatinLogic.DoSomeDuplicatingStuff();
}
}
public class SortOfWrapPanel : WrapPanel
{
private readonly PanelPresentatinLogic _panelPresentatinLogic;
public SortOfWrapPanel(PanelPresentatinLogic presentationLogic)
{
_panelPresentatinLogic = presentationLogic;
_panelPresentatinLogic.Panel = this;
}
public void DoSomeDuplicatingStuff()
{
_panelPresentatinLogic.DoSomeDuplicatingStuff();
}
}
public class UsageSample
{
public void PopulateCollectionOfItemsDependingOnConfigHopeYouveGotTheIdea()
{
string configValue = configuration["PanelKind"];
PanelPresentatinLogic panelPresentatinLogic = new PanelPresentatinLogic();
Panel panel = configValue == "Wrap"
? new SortOfWrapPanel(panelPresentatinLogic)
: new SortOfStackPanel(panelPresentatinLogic);
// TODO: add panel to GUI
}
}
Upvotes: 1
Reputation: 2321
May be you can use Panel?
public class ContainerBase : <wrap or stack>
{
//Do stuff!
}
Upvotes: 0
Reputation: 3915
You can use Generics for this;
public class ContainerBase<T> where T : Panel
You can then use the config setting to initialize the right type.
Upvotes: 1