在UserControl内设置WPF DatePicker的StringFormat

问题描述 投票:0回答:1

我有一个自定义WPF用户控件,其中使用了DatePicker。我正在使用提供的答案设置DatePicker的显示格式at this SO article

<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的依赖项属性。

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

希望的理由

c# wpf wpf-controls
1个回答
1
投票

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

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

[您可以在DateDisplayFormat中定义一个CustomControl依赖项属性(我想您已经完成),然后重写OnApplyTemplate方法并以编程方式创建TextBox的绑定。

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

© www.soinside.com 2019 - 2024. All rights reserved.