在WPF中,是否可以为通用基础控件提供默认样式?
假设我有以下基类:
public abstract class View<T> : ContentControl
where T : ViewModel
{
static View()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(View<T>),
new FrameworkPropertyMetadata(typeof(View<T>)));
}
// Other properties, methods, etc in here
}
public abstract class ViewModel
{
// Other properties, methods, etc in here
}
那么假设我有两个继承自这些基类的类:
public partial class TestView : View<TestViewModel>
{
public TestView()
{
InitializeComponent();
}
// TestView specific methods, properties, etc
}
public class TestViewModel : ViewModel
{ /* TestViewModel specific methods, properties, etc */ }
现在我想为所有派生控件使用的基础控件提供默认样式:
<Style TargetType="{x:Type local:View`1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:View`1}">
<Border Background="Magenta"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel>
<Button>Test</Button>
<ContentPresenter ContentSource="Content" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然而,当我使用我的TestView控件时,模板标记没有被应用(因此,在我定义在TestView控件的XAML中的任何内容都不在视觉/逻辑树中)。
我基本上试图采取我的基本视图/视图模型类并应用一致的外观和感觉。当然,这在非泛型基本视图情况下是有效的。然而,我需要视图和视图模型之间的类型安全连接,以便我可以从任何引用视图的地方调用视图模型的方法(我知道这可能不符合某些人实施MVVM的方式)。