简体   繁体   中英

Windows Universal UserControl Binding

I have created a UserControl for a Windows Universal app.

I have a property in my code behind file called HourList defined thus...

internal ObservableCollection<int> HourList = 
     new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
                           12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

I want to use the HourList to bind controls to within my UserControl's xaml, for example...

<ListView Width="100" ItemsSource="{Binding HourList, ElementName=timePicker}"
</ListView>

This assumes that I have named my UserControl like this...

<UserControl x:Name="timePicker"

When I place the control on a page however, my listview doesn't contain a list of hours as I expect.

What have I missed?

You can simply create a property in the code-behind of your user control:

public ObservableCollection<int> HourList
{
    get;
    set;
}
public UserControl()
{
    this.InitializeComponent();
    HourList = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
    10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };                
}

However at some point if you need to bind to it or do animations, then you will need it to be a dependency property like below:

public static readonly DependencyProperty HourListProperty =
    DependencyProperty.Register("HourList",
    typeof(ObservableCollection<int>), typeof(MyUserControl1), 
    new PropertyMetadata(new ObservableCollection<int> 
    { 
      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
      14, 15, 16, 17, 18, 19, 20, 21, 22, 23 
    }));

public ObservableCollection<int> HourList
{
    get
    {
        return (ObservableCollection<int>)this.GetValue(HourListProperty);
    }

    set
    {
        this.SetValue(HourListProperty, value); 
    }
}

Either way the XAML is the same:

<StackPanel>
    <UserControl x:Name="timePicker" />
        <ListView         
        Height="100"
        Foreground="Black"            
        Width="100" 
        ItemsSource="{Binding ElementName=timePicker, Path=HourList}">
        </ListView>
</StackPanel>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM