C# WPF-从变量类继承的类
我有一个应用程序,可以以两种不同的方式显示项目,一种是使用StackPanel以行显示,另一种是使用WrapPanel以图标显示。显示这些项目的方式取决于配置设置。为了填充这些面板,我有两个独立的类,一个从WrapPanel继承,另一个从StackPanel继承。我能够使用一个接口减少重复的代码。然而,我仍然有很多重复的代码,代码之间的唯一区别是对StackPanel或WrapPanel的引用 我真正想做的是根据配置设置创建一个从StackPanel或WrapPanel继承的类C# WPF-从变量类继承的类,c#,wpf,inheritance,C#,Wpf,Inheritance,我有一个应用程序,可以以两种不同的方式显示项目,一种是使用StackPanel以行显示,另一种是使用WrapPanel以图标显示。显示这些项目的方式取决于配置设置。为了填充这些面板,我有两个独立的类,一个从WrapPanel继承,另一个从StackPanel继承。我能够使用一个接口减少重复的代码。然而,我仍然有很多重复的代码,代码之间的唯一区别是对StackPanel或WrapPanel的引用 我真正想做的是根据配置设置创建一个从StackPanel或WrapPanel继承的类 public c
public class ContainerBase : <wrap or stack>
{
//Do stuff!
}
公共类容器库:
{
//做事!
}
这可能吗?我的处理方法有误吗?您可以使用它
public class ContainerBase<T> where T : Panel
公共类容器基础,其中T:Panel
然后可以使用配置设置初始化正确的类型。是否可以使用面板
public class ContainerBase : <wrap or stack>
{
//Do stuff!
}
公共类容器库:
{
//做事!
}
当我在第一条评论中说“组合而非继承”时,我的意思是smth,如下所示:
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
}
}
在WPF中,不要使用控件来填充自身。相反,使用MVVM模式 只需一个类提供数据(通常是一个ObservableCollection)并将“视图模式变量”加载到MVVM的属性中,就可以实现您的目标
然后,您可以使用带有的项目面板来选择视图。这看起来像是解决方法。。。不要认为这是正确的方法。在这里使用合成而不是继承如何?使用模板和样式如何?@KarelFrajtak,templates and styles(+template selector)是我想到的第一件事,但我没有足够的经验来推荐在这种情况下有用的smth。但本质上是的-模板和样式听起来很合理。@Fred,我添加了answer+代码来说明我在第一篇评论中的意思。你肯定应该学习如何使用DataTemplateSelector和MVVM来处理WPF,它需要的代码比你正在尝试的要少得多。这假设(可能是正确的)OP只需要
面板
提供的任何一个类中的方法,或者可以重构他的代码来实现这一点。