0

I have a custom WPF UserControl that uses a DatePicker within it. I'm setting the display format of the DatePicker using the answer provided 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>

I would like to use a different format string for different instances of the control, so I'd like in some way to provide the format when I add the UserControl to the form, something like

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

Label and LabelWidth are Dependancy properties of the custom UserControl.

Is it possible to have bind the StringFormat to a control property, when it is inside a Binding ? If not, is there a way to do what I want to do?

Hope that makes sense

0

1 Answer 1

1

Is it possible to have bind the StringFormat to a control property, when it is inside a Binding ?

No. You can't bind the StringFormat property of a Binding because it's not a dependency property.

What you could to is to define a DateDisplayFormat dependency property in your CustomControl (which I guess you have done already) and then override the OnApplyTemplate method and create the binding of the TextBox programmatically.

Alternatively, you could use a <MultiBinding> in the XAML markup that binds to both SelectedDate and DateDisplayFormat and use a multi converter that returns a string.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried to use MultiBinding, and it works when I set the value from code. However, when I change the value using the DatePicker, it reverts to a standard dd/MM/yy date format. I do have a DateDisplayFormat dep property so I'll try that next
@IanBoggs: Your multi converter should be called whenever SelectedDate is set and you can then return whatever string you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.