Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF UserControl.Resources reference

I am try to start learning WPF and i am using Telerik. So i start with simple ComboBox in this article and this is my control:

<telerik:RadComboBox Height="20" Width="200" ItemsSource="{Binding Source={StaticResource DataSource}, Path=Agency}"></telerik:RadComboBox>

What i am trying to do now is to bind an object but first to declare a resource in the XAML (from the article):

<UserControl.Resources>
    <example:AgencyViewModel x:Key="DataSource"/> // AgencyViewModel is a class 
</UserControl.Resources>

So my problem is that after UserControl i don't have the option Resources, i try to put it inside my control, so i be happy to understand how this is working in WPF

like image 311
fgerh drgse Avatar asked Dec 29 '14 19:12

fgerh drgse


1 Answers

You have to set the DataContext dependency property on a parent control in relation to your ComboBox. The DataContext is then inherited by all (logical-)children. You can then bind to properties on the object referenced by the DataContext dependency property. You do that by referencing the x:Key of your resource with a StaticResource Markup Extension construct.

<UserControl>
  <UserControl.Resources>
    <example:AgencyViewModel x:Key="DataSource"/> // AgencyViewModel is a class 
  </UserControl.Resources>

  <Grid DataContext="{StaticResource DataSource}">

    <telerik:RadComboBox Height="20" Width="200" 
        ItemsSource="{Binding ItemsCollectionDefinedInViewModel}" />

  </Grid>
</UserControl>

You can also do it as it is done in the article without setting the DataContext but instead setting the Source of the binding explicilty.

ItemsSource="{Binding Source={StaticResource DataSource}, Path=Agency}"
like image 52
user1182735 Avatar answered Oct 02 '22 23:10

user1182735