Question

I have to create in my XAML file a static resource.

<Window.Resources>
    <vm:ViewModel x:Key="viewModel" />
</Window.Resources>

I need this static resource to get the items for my combobox

ItemsSource="{Binding Source={StaticResource viewModel}, Path=GetItems, Mode=TwoWay}"

But how can I give the ViewModel (constructor) a instance of my code behind class?

Was it helpful?

Solution

If I understand this correctly, you are violating the MVVM pattern. You should never provide items from the ComboBox into your VM. You should rather provide the items from you VM and bind it to the Combobox, and the you don't have problems accessing the items.

OTHER TIPS

As far as I understand you want to bind your view and viewmodel according to the MVVM pattern.

You should not reference your viewmodel directly in your view, otherwise you have a strong coupling between them. According to the MVVM pattern, you should couple them by the DataContext

In code behind (for example in file App.xaml.cs) it looks like that

yourWindow.DataContext = yourViewModel

Then in your viewmodel class you will have a property named GetItems

Finally in your window you bind your listbox to GetItems

ItemsSource="{Binding GetItems, Mode=TwoWay}"

Well, you can do it from the code, I mean everything from the code, or you can try (depends on how your app architcted) , by using ObjectDataProvider.

For example:

<ObjectDataProvider ObjectType="{x:Type ViewModel}"  x:Key="viewModel">
      <ObjectDataProvider.ConstructorParameters>
                <StaticResource ResourceKey="dataProvider"/>
       </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider >

In this case, naturally, the parameter you pass to ctor of the povoder, have to be a resource too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top