How can I bind a TextBlock to an ObjectDataProvider resource defined in app.xaml?

无人久伴 提交于 2019-12-08 12:24:22

问题


I have a WPF application with MVVM, it has an Ap.XAML that looks like this.

 <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/StyleDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <ObjectDataProvider x:Key="SAG_POK" ObjectType="{x:Type or:SAG_POK}" />
    </ResourceDictionary>        
</Application.Resources>

Now, on the MainWindow.XAML I want to bind to the SAG_POK ObjectDataprovider in Ap.xaml.

<StackPanel
   DataContext="{Binding Source={StaticResource SAG_POK}}">
   <TextBlock Name="ValgtSag" Text="{Binding ToStringProperty}"/>
</StackPanel>

My problem is that in one of my viewmodels, I instantiate the SAG_POK ObjectDataProvider in App.xaml with an instance of SAG_POK.

App.Current.Resources["SAG_POK"] = SagSelecteditem;

But I can't figure out where to put my OnNotifyPropertyChanged("SAG_POK") I have tried different scenarios but none of them seems to work.

Anyone who has tried this before ?, please let me know of any hints, thanks in advance.


回答1:


you can do this

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/StyleDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <!--<ObjectDataProvider x:Key="SAG_POK" ObjectType="{x:Type or:SAG_POK}" />-->
        <local:MainViewModel x:Key="SAG_POK" />
    </ResourceDictionary>        
</Application.Resources>


<StackPanel DataContext="{Binding Source={StaticResource SAG_POK}}">
   <TextBlock Name="ValgtSag" Text="{Binding ToStringProperty}"/>
</StackPanel>

App.Current.Resources["SAG_POK"].SelectedItem = SagSelectedItem;

MainViewModel is yout main view model :-) in the hole application

hope this helps



来源:https://stackoverflow.com/questions/8150401/how-can-i-bind-a-textblock-to-an-objectdataprovider-resource-defined-in-app-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!