Search code examples
wpfpropertiesuser-controlsvisibility

How to handle visibilty of properties in an UserControl?


I try to create a custom "TimePicker" - UserControl and struggle a bit with the design of the code.

In the XAML of the UserControl I created a ComboBox, which binds to a List<int> HoursList-property. This will contain all numbers from 0-23. I want to create a DependencyProperty Hour to keep track of the selected ComboBox Item via Binding in an other XAML file later.

TimePicker.xaml

<Grid>
    <!--Hours-->
    <ComboBox Grid.Column="0" ScrollViewer.CanContentScroll="False"
            ItemsSource="{Binding HoursList,RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
            SelectedIndex="0" ItemStringFormat="{}{0:00}">
    </ComboBox>
</Grid>

TimePicker.xaml.cs

public partial class TimePicker : UserControl
{
    private List<int> hoursList;
    public readonly List<int> HoursList
    {
        get 
        {
            if (this.hoursList == null)
                LoadHoursList();

            return hoursList; 
        }
    }

    public TimePicker()
    {
        InitializeComponent();
    }

    /// <summary>
    /// will create a new List<int> and fill it from 0-23 (int) representing the hours 
    /// </summary>
    private void LoadHoursList()
    {
        this.hoursList = new List<int>();

        for (int i = 0; i < 24; i++)
            this.HoursList.Add(i);
    }
}

If I use the Control now in another XAML-file, it will look like this:

Test.xaml

<my:TimePicker Margin="2"  />

My problem is that I can acess the HoursList-Property here. But it should be used for loading up the default values in the control only. Access should be possible with a DependencyProperty Hour later..So I want to keep the HoursList hidden.

Here an example that I want to forbid:

<my:TimePicker Margin="2" HoursList="" />

Maybe I did not understand the mechanics correctly..any advice is appricated!


Solution

  • You may not declare a public property at all, but just assign the ComboBox's ItemsSource in code behind:

    <ComboBox x:Name="cbHours" .../>
    

    Code:

    public TimePicker()
    {
        InitializeComponent();
        cbHours.ItemsSource = Enumerable.Range(0, 24);
    }