问题
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?
回答1:
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.
回答2:
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}"
回答3:
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.
来源:https://stackoverflow.com/questions/10349209/static-resource-constructor-with-parameters