我不確定您是否可以爲Label和DatePicker設置DefaultInputStyle。什麼是DefaultInputStyle的TargetType?如果您將在多個應用程序中使用此自定義控件,建議使用自定義控件。如果你想創建自定義控件,你需要繼承控件,創建一些依賴屬性,重寫DefaultStyleKeyProperty。
public class MyCoolControl : Control
{
public Style LabeStyle
{
get { return (Style)GetValue(LabeStyleProperty); }
set { SetValue(LabeStyleProperty, value); }
}
public static readonly DependencyProperty LabeStyleProperty =
DependencyProperty.Register(
"LabeStyle", typeof(Style), typeof(MyCoolControl));
public Style DatePickerStyle
{
get { return (Style)GetValue(DatePickerStyleProperty); }
set { SetValue(DatePickerStyleProperty, value); }
}
public static readonly DependencyProperty DatePickerStyleProperty =
DependencyProperty.Register(
"DatePickerStyle", typeof(Style), typeof(MyCoolControl));
public object LabelContent
{
get { return (object)GetValue(LabelContentProperty); }
set { SetValue(LabelContentProperty, value); }
}
public static readonly DependencyProperty LabelContentProperty =
DependencyProperty.Register(
"LabelContent", typeof(object),
typeof(MyCoolControl), new PropertyMetadata(null));
static MyCoolControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(MyCoolControl),
new FrameworkPropertyMetadata(typeof(MyCoolControl)));
}
}
定義隱含風格MyCoolControl在主題/ Generic.xaml:
<Style TargetType="local:MyCoolControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<Label Content="{TemplateBinding LabelContent}" Style="{TemplateBinding LabeStyle}" />
<DatePicker Style="{TemplateBinding DatePickerStyle}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然後你可以使用自定義控制:
<local:MyCoolControl Grid.Row="0" Grid.Column="0"
LabelContent="Boom" DatePickerStyle="{StaticResource DefaultInputDatePickerStyle}"
LabelStyle="{StaticResource DefaultInputLabelStyle}" />
我有沒有這樣的MVC的,但會你也可以在wpf中使用。 – Saravanan 2015-01-04 11:05:12
MVC創建一個HTML標記並在客戶端動態設置它。 WPF能夠編譯時間,所以我不確定這些是如何翻譯的。你能否給出一個關於如何聲明如此複雜控制的例子?或建議在評論關鍵詞集中? – 2015-01-04 11:10:40
注意:我想你是在討論一個'UserControl'而不是'custom control'。對於區別請參閱:http://wpftutorial.net/CustomVsUserControl.html – 2015-01-04 11:58:52