平時WPF架構:在WPF
public partial class MainWindow: Window {
... InitializeComponent()
}
XAML: <Window x:Class="MainWindow"> </Window>
我想移動到:
public abstract class BaseWindow: Window {
public System.Windows.Controls.TextBlock control1;
public System.Windows.Shapes.Rectangle control2;
public System.Windows.Controls.TextBox control3;
}
public partial class AWindowImplementation {
... InitializeComponent()
}
public partial class AnotherWindowImplementation{
... InitializeComponent()
}
XAML:
<BaseWindow x:Class="AWindowImplementation"> </BaseWindow>
<BaseWindow x:Class="AnotherWindowImplementation"> </BaseWindow>
以上是僞代碼。這個新的體系結構編譯,並警告實現隱藏控件定義(因爲我應該把'override'關鍵字放在自動生成的InitializeComponent的地方)。不幸的是,控制字段不會被填充。
這是可以實現的嗎?我正在嘗試的是使用相同的界面/控件創建多個UI設計,以便其餘代碼可以與任一設計進行交互。
編輯:感謝pchajer和葉夫根尼·,我現在有以下工作解決方案,但我仍然可以覆蓋警告:
public class MainWindowBase : Window
{
public TextBlock control1;
public Rectangle control2;
public TextBox control3;
static MainWindowBase()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MainWindowBase),
new FrameworkPropertyMetadata(typeof(MainWindowBase)));
}
public override void OnApplyTemplate()
{
control1 = (TextBlock) FindName("control1");
control2 = (Rectangle) FindName("control2");
control3 = (TextBox) FindName("control3");
}
}
<Style TargetType="{x:Type views:MainWindowBase}"
BasedOn="{StaticResource {x:Type Window}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type views:MainWindowBase}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
public partial class AWindowImplementation :MainWindowBase {
... InitializeComponent()
}
<MainWindowBase x:Class="AWindowImplementation"> </MainWindowBase>
我想我會在基類中使用不同的字段名稱擺脫警告,或者可能刪除派生類中的InitializeComponent。但無論如何它現在起作用。
你說的是重寫,你有抽象方法嗎? –
不,只是在抽象類中定義的字段是由子類中的自動生成的InitializeComponent代碼再次定義的。 –