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 re开发者_如何学运维gards, Peter Larsson
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 =)
Its not because you might have a spelling mistake
Path=DataContext.PartGruppAll
might should be
Path=DataContext.PartGroupAll
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.
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.
精彩评论