【问题标题】:Setting StringFormat of WPF DatePicker inside UserControl在 UserControl 中设置 WPF DatePicker 的 StringFormat
【发布时间】:2019-11-04 15:24:49
【问题描述】:

我有一个自定义 WPF UserControl,它在其中使用 DatePicker。我正在使用提供的答案 at this SO article

设置 DatePicker 的显示格式
<Style TargetType="{x:Type DatePickerTextBox}" BasedOn="{StaticResource {x:Type DatePickerTextBox}}">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <TextBox x:Name="PART_TextBox"
                    Text="{Binding Path=SelectedDate, StringFormat='dd-MM-yy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我想为控件的不同实例使用不同的格式字符串,所以我想在将 UserControl 添加到表单时以某种方式提供格式,例如

<basecontrols:CustomControl 
    LabelWidth="{StaticResource LabelColumnWidth}" 
    Label="Custom Information" 
    DateDisplayFormat="dd-MMMM-yyyy" 
    />

Label 和 LabelWidth 是自定义 UserControl 的 Dependancy 属性。

是否可以将 StringFormat 绑定到控件属性,当它位于 Binding 中时?如果没有,有没有办法做我想做的事?

希望这是有道理的

【问题讨论】:

    标签: c# wpf wpf-controls


    【解决方案1】:

    StringFormat 位于Binding 内时,是否可以将StringFormat 绑定到控件属性?

    没有。您不能绑定 BindingStringFormat 属性,因为它不是依赖属性。

    您可以在您的CustomControl 中定义一个DateDisplayFormat 依赖属性(我猜您已经这样做了),然后覆盖OnApplyTemplate 方法并以编程方式创建TextBox 的绑定。

    或者,您可以在绑定到SelectedDateDateDisplayFormat 的XAML 标记中使用&lt;MultiBinding&gt;,并使用返回string 的多转换器。

    【讨论】:

    • 我尝试过使用 MultiBinding,当我从代码中设置值时它可以工作。但是,当我使用 DatePicker 更改值时,它会恢复为标准的 dd/MM/yy 日期格式。我确实有一个 DateDisplayFormat dep 属性,所以我会尝试下一个
    • @IanBoggs:只要设置了SelectedDate,就应该调用您的多转换器,然后您可以返回任何您想要的字符串。
    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多