是否可以为 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 的方式)。