wpfxamltimecomboboxobjectdataprovider

WPF time dropdown box with objectdataprovider


I'm trying to implement a user control for choosing time with 3 comboboxes - one for hours, second for minutes and third for seconds.

Hours' combobox has numbers from 0 to 23 to choose from

Minutes' and seconds' combobox has numbers 0 to 59 to choose from

I believe I can do it just with XAML without needing to fill the comboboxes dynamically in the codebehind.

<ComboBox x:Name="HoursComboBox">
    <ComboBoxItem>0</ComboBoxItem>
    <ComboBoxItem>1</ComboBoxItem>
    ...
    <ComboBoxItem>23</ComboBoxItem>
</ComboBox>

But this looks like a lot of static and unneccessary code. I can fill the combobox with just one line in the codebehind like this.

HoursComboBox.ItemsSource = System.Linq.Enumerable.Range(0, 23);

Can I implement this call just in XAML?


Solution

  • Turns out I can.

    <UserControl x:Class="MyControls.TimeSpanSelector"
                 xmlns:linq="clr-namespace:System.Linq;assembly=System.Core"
                 ...>
    
        <UserControl.Resources>
            <ObjectDataProvider x:Key="Hours"
                                ObjectType="{x:Type linq:Enumerable}"
                                MethodName="Range">
                <ObjectDataProvider.MethodParameters>
                    <sys:Int32>0</sys:Int32>
                    <sys:Int32>23</sys:Int32>
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </UserControl.Resources>
    
        ...
    
        <Border>
            <ComboBox ItemsSource="{Binding Source={StaticResource Hours}}" />
        </Border>
    
        ...
    
    </UserControl>