WPF UserControl.Resources reference
Asked Answered
A

1

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

Ahearn answered 29/12, 2014 at 19:32 Comment(2)
Try to search on Telerik site for how to use RadComboBoxPeriodontics
This is what i try, am i doing something wrong ?Ahearn
A
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}"
Ageless answered 29/12, 2014 at 19:41 Comment(4)
And this 2 ways are the same ?Ahearn
Please see my control update, i try the second way and got compiler error: the resource "DataSource" could not resolvedAhearn
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 msdn.microsoft.com/en-us/library/ms750612%28v=vs.110%29.aspxAgeless
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.Ageless

© 2022 - 2024 — McMap. All rights reserved.