我想创建一个自定义布局,虽然我似乎无法找到正确的方法 . 自定义布局的目的是成为具有某些行为的模板 .
Under是我尝试过的(在其他一些东西中) .
代码 - 简化:
public class MyComponent : StackLayout {
public MyComponentHeader Header { get; set; }
/* Somewhat feels wrong to add this as a property */
public class MyComponentHeader : StackLayout {
}
/* Somewhat feels wrong to add this as a property */
public MyComponentBody Body { get; set; }
public class MyComponentBody : StackLayout {
}
}
用法 - 呃...:
<common:MyComponent>
<common:MyComponent.Header>
<Label Text="Cool header!"/>
</common:MyComponent.Header>
<common:MyComponent.Body>
<Label Text="Cool body!"/>
</common:MyComponent.Body>
</common:MyComponent>
我希望在这种情况下将“Header”和“Body”与普通StackLayout或其他布局分开的原因是因为我想要控制项目,因为它们是行为的一部分 . 我不想使用类似的东西:给我带x:Name = Header的孩子,因为这必然会失败 .
我希望这是可能的:)
谢谢!
1 回答
WPF及其后续UWP专门针对MVVM模式而设计 . 虽然你可以使用其他模式甚至是WinForms时代的方法,但这样做会错过90%的功率并遇到全新的问题 .
而不是使用自定义控件(与DataContext有各种各样的问题),你应该使用我称之为“类型目标数据模板” .
几年前我写了一篇关于MVVM的介绍 . 它应该让你走在正确的轨道上:https://social.msdn.microsoft.com/Forums/vstudio/en-US/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2/lets-talk-about-mvvm?forum=wpf