如何将TextBlock绑定到app.xaml中定义的ObjectDataProvider资源?

问题描述:

我有一个带有MVVM的WPF应用程序,它具有一个如下所示的Ap.XAML.

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>

现在,在MainWindow.XAML上,我想绑定到Ap.xaml中的SAG_POK ObjectDataprovider.

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>

我的问题是,在我的一个视图模型中,我使用SAG_POK的实例实例化了App.xaml中的SAG_POK ObjectDataProvider.

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;

但是我不知道将OnNotifyPropertyChanged("SAG_POK")放在哪里,但是我尝试了不同的方案,但是似乎都不起作用.

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.

您可以这样做

<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是孔应用程序中的主视图模型:-)

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

希望这会有所帮助