1

我们以前在我以前的工作中这样做过,它在那里工作得很好,但由于某种原因,我现在无法让它工作。

我只想使用 ObjectDataProvider 在 XAML 中创建 ViewModel 类的实例,以便我可以引用它进行绑定,并且我已经在 Window 上将 DataContext 设置为 ViewModel,并且我有一个 xmlns:local与我的所有 ViewModel 具有相同命名空间的完全限定名称。

<Window 
x:Class="TimersXP.TimersHost"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:TimersXP.ViewModels"
Name="TimersHostView"
SizeToContent="Height"
Title="TimersXP"
WindowStartupLocation="CenterScreen"
WindowStyle="ToolWindow"
DataContext="TimersHostViewModel">
<Window.Resources>
    <ObjectDataProvider x:Key="TimersHostViewModel" ObjectInstance="{x:Type local:TimersHostViewModel}"/>
</Window.Resources>

后来我尝试使用 ViewModel:

<Grid.ContextMenu>
        <ContextMenu ItemsSource="{Binding Source={StaticResource TimersHostViewModel}, Path=Skins}" Style="{DynamicResource styleBanner}"/>
</Grid.ContextMenu>

但我的问题是,当我在 TimersHostViewModel 无参数构造函数中设置断点时,调试时它们永远不会被命中。所以似乎 ObjectDataProvider 没有正确地完成它的工作。尽管确实创建了窗口。

我可以看到我的 App.xaml.cs 和 MainWindow.xaml.cs 中的断点被击中,InitializeComponent 也被击中,甚至我的单例模型类也被创建。但是我一辈子都无法弄清楚为什么我的 TimersHostViewModel 类构造函数从未被调用过。

我记得的一件事是,在我的工作中,我们使用了这样的一行:

我看到没有 ObjectInstance,只有 ObjectType,所以当我尝试删除 ObjectInstance 并改为设置 ObjectType 时,我收到以下错误:对象引用未设置为对象的实例,它突出显示 ObjectType=" {x:Type local:TimersHostViewModel}"...什么给出了?!为什么它在一种情况下有效,而在另一种情况下无效?我对此很困惑。

编辑:好的,我能够部分回答我自己的问题,但真正的问题仍然存在。因此,我能够通过删除 Window 的 DataContext 并将 ObjectDataProvider ObjectInstance 更改为 ObjectType 来调用 ViewModel 构造函数。然后将 Grid DataContext 设置为绑定到 TimersHostViewModel。但这仍然让我现在在 ObjectDataProvider ObjectType 上遇到这个设计时/编译时错误:对象引用未设置为对象的实例。

<Window 
x:Class="TimersXP.TimersHost"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:TimersXP.ViewModels"
Name="TimersHostView"
SizeToContent="Height"
Title="TimersXP"
WindowStartupLocation="CenterScreen"
WindowStyle="ToolWindow">
<Window.Resources>
    <ObjectDataProvider x:Key="TimersHostViewModel" ObjectType="{x:Type local:TimersHostViewModel}"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource TimersHostViewModel}}">

也仍然不确定为什么它在某些情况下会起作用,但在其他情况下不起作用,比如我现在使用的那种。

完整的源代码在这里: http ://timersxp.codeplex.com/SourceControl/latest#VS2013/TimersXP/Views/TimersHost.xaml

4

1 回答 1

0

必须将 IsAsynchronous="True" 属性添加到 ObjectDataProvider,然后一切正常!感谢这个线程的提醒! http://forums.asp.net/t/1344386.aspx?How+to+create+a+flipcart+like+panel+for+showing+products+in+gridview

于 2014-02-04T00:37:58.563 回答