Dot-Net
自定義 WPF DatePickerTextBox 模板
我正在嘗試
TextBox在DatePicker控制項中使用自定義,但我無法將日期從彈出日曆綁定到TextBox. 我不想對整個進行樣式化,DatePicker除非我必須這樣做,並且DatePickerTextBox它有自己的控制,所以必須有一種方法來改變它。下面的程式碼是我作為開始的程式碼:<Style TargetType="{x:Type DatePickerTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DatePickerTextBox}"> <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate}" /> </ControlTemplate> </Setter.Value> </Setter> </Style>我可能沒有正確進行綁定,或者
PART_TextBox可能不正確,因為它不是DatePicker模板本身的一部分。有人請幫忙!:)
提前致謝!
試試這個:
<DatePicker> <DatePicker.Resources> <Style TargetType="{x:Type DatePickerTextBox}"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </DatePicker.Resources> </DatePicker>
我意識到這個問題已經回答了很長時間,但是直接綁定到DatePicker的 Text 屬性將允許控制項模板中的TextBox輕鬆地接受DatePicker提供的 Short/Long 格式。
<DatePicker> <DatePicker.Resources> <Style TargetType="{x:Type DatePickerTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <TextBox Text="{Binding Text, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </DatePicker.Resources> </DatePicker>“PART_TextBox”也不是必需的,因為它不是DatePickerTextBox模板的一部分。DatePickerTextBox包含的唯一 PART是:
[TemplatePart(Name = DatePickerTextBox.ElementContentName, Type = typeof(ContentControl))] public sealed partial class DatePickerTextBox : TextBox private const string ElementContentName = "PART_Watermark";並繼承自TextBoxBase …
[TemplatePart(Name = "PART_ContentHost", Type = typeof(FrameworkElement))] public abstract class TextBoxBase : Control internal const string ContentHostTemplateName = "PART_ContentHost";替代解決方案: 如果您選擇不使用TextBox並使用繼承的 PART,您將能夠更改DatePickerTextBox,而無需更改控制項的預設功能。
<DatePicker> <DatePicker.Resources> <Style TargetType="{x:Type DatePickerTextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Grid SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"/> <ScrollViewer Name="PART_ContentHost" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </DatePicker.Resources> </DatePicker>