6

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

cel sharp
  • 149
  • 9
fgerh drgse
  • 61
  • 1
  • 1
  • 3

1 Answers1

8

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}"
user1182735
  • 764
  • 9
  • 21
  • 1
    And this 2 ways are the same ? – fgerh drgse Dec 29 '14 at 20:09
  • 1
    Please see my control update, i try the second way and got compiler error: the resource "DataSource" could not resolved – fgerh drgse Dec 29 '14 at 20:14
  • 1
    No. A Binding must have a source!!! In the first case (my code) WPF sets the source of the binding to the object that is referenced by the datacontext. This happens when no source, relativesource or elementname are specified in a binding expression. In the second case the source is set explicitly. I recommend you read http://msdn.microsoft.com/en-us/library/ms750612%28v=vs.110%29.aspx – user1182735 Dec 29 '14 at 20:15
  • 1
    The resource key that you reference with the staticresource markup extension has to be defined in the resuorce section on a parent element and in the same namescope, i.e. same tree structure. For more help please post the entire xaml. – user1182735 Dec 29 '14 at 20:18