我想为WPF日期选择器控件添加屏蔽功能。我看到DatePickerTextBox无法进一步扩展。
所以,我决定添加一个交互行为。我使用以下代码:
蒙面日期选择器类:
public class MaskedDatePicker : DatePicker
{
}
我创建了一个附加行为,如下所示:
public class DatePickerTextBoxInputMaskBehavior : Behavior<DatePickerTextBox>
{
}
现在在模板中我附加了行为:
<DatePickerTextBox x:Name="PART_TextBox"
Grid.Row="0"
Grid.Column="0"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Focusable="{TemplateBinding Focusable}"
Foreground="{TemplateBinding Foreground}">
<i:Interaction.Behaviors>
<cleanPoc:DatePickerTextBoxInputMaskBehavior />
</i:Interaction.Behaviors>
</DatePickerTextBox>
现在,每次我从datepicker应用程序中打开日历时都会冻结,因为DatePickerTextBoxInputMaskBehavior中的文本已被递归触发。 知道如何处理吗?
答案 0 :(得分:1)
基本控件(DatePicker)通过将行为附加到DatePickerTextBox而无法实际控制的DatePickerTextBox ...
获取对MaskedDatePicker控件本身的引用,并在控件的SelectedDate属性设置为新值时设置DatePickerTextBox的Text属性。请查看以下示例,如果您需要任何说明,请告诉我。
祝你好运! public class DatePickerTextBoxInputMaskBehavior : Behavior<DatePickerTextBox>
{
...
containing the event data.
private void AssociatedObjectLoaded(object sender, System.Windows.RoutedEventArgs e)
{
this.Provider = new MaskedTextProvider(this.InputMask, CultureInfo.CurrentCulture);
this.Provider.Set(this.AssociatedObject.Text);
this.Provider.PromptChar = this.PromptChar;
this.SetText(this.Provider.ToDisplayString());
MaskedDatePicker dp = FindVisualParent<MaskedDatePicker>(this.AssociatedObject);
var textProp = DependencyPropertyDescriptor.FromProperty(MaskedDatePicker.SelectedDateProperty, typeof(MaskedDatePicker));
if (textProp != null)
{
textProp.AddValueChanged(dp, OnHandler);
}
}
private static T FindVisualParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindVisualParent<T>(parent);
}
private void OnHandler(object s, EventArgs args)
{
this.UpdateText();
}
private void UpdateText()
{
if (this.Provider.ToDisplayString().Equals(this.AssociatedObject.Text))
{
return;
}
MaskedDatePicker dp = FindVisualParent<MaskedDatePicker>(this.AssociatedObject);
if (dp != null && dp.SelectedDate.HasValue)
SetText(dp.SelectedDate.Value.ToString("dd/MM/yyyy")); //format date here...
}
/// <summary>
/// Sets the text.
/// </summary>
/// <param name="text">The text.</param>
private void SetText(string text)
{
this.AssociatedObject.Text = string.IsNullOrWhiteSpace(text) ? string.Empty : string.Format(CultureInfo.CurrentCulture, text.ToString(CultureInfo.CurrentCulture.DateTimeFormat));
}
}
}