views:

83

answers:

4

I'm new to WPF and the MVVM pattern so I have some problems with my bindings.

In a details view of a customer, I want to list some statuses in a combobox.

In my ViewModel the customer is at the root level, and so is the list of statuses.

When using a static resource, I can use:

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=DataContext.PartGruppAll}"

on my ComboBox, but when I set the DataContext from code behind, it does not work, what am I doing wrong, in my opinion it should make no difference.

Best regards, Peter Larsson

A: 

Its not because you might have a spelling mistake

Path=DataContext.PartGruppAll

might should be

Path=DataContext.PartGroupAll
aqwert
No, sorry, there is a part of Swedish in that name, the correct name actually is PartGruppAll. :)
Peter Larsson
Ok, no worries... was just a hunch
aqwert
A: 

Oh one more thing...

If the StackPanel is up the same visual tree as the combo box then you dont need to find it in the binding

ItemsSource="{Binding PartGruppAll}" 

Should work as DataCoxtext's are searched up the visual tree.

aqwert
No, that doesn't work either.
Peter Larsson
A: 

I'll try to give you some more details, the viewmodel is quite large so I'll try to shorten it.

I instantiate the viewmodel in my code behind for App.xaml

        protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        PartWindow pw = new PartWindow();


        var PartViewModel = new ViewModel.PartWindowViewModel();
        pw.DataContext = PartViewModel;

        pw.Show();
    }

Then in my page I bind the data to a stackpanel:

<StackPanel DataContext="{Binding Path=PartViewModel}">

I then display the Customer in a grid by binding to the Customer-property SelectedPart.

   <Grid DataContext="{Binding SelectedPart}" Margin="5" Grid.Column="0">

My viewModel Looks like this:

ViewModelClass

  • SelectedPart

Name and other properties

  • StatusList

Name and other properties

Nothing really complicated I think... The grid is tied to the selected customer, that's the problem.

Peter Larsson
A: 

In your binding, try setting AncestorType to your view class. Something like

ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vw:MyView}}, Path=DataContext.PartGruppAll}"

where vw is your namespace where you keep you view and MyView is the name of your view class itself.

In my application I have declared vw like this

xmlns:vw="clr-namespace:MyApp.View"

(You probably didn't need that bit but I included just in case =)

toomeke