Static resource constructor with parameters

2019-07-22 04:36发布

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?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-22 05:05

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.

查看更多
Lonely孤独者°
3楼-- · 2019-07-22 05:15

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}"
查看更多
等我变得足够好
4楼-- · 2019-07-22 05:20

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.

查看更多
登录 后发表回答