开发者

Passing existing object instances as constructor parameters to the ObjectDataProvider in WPF

I am trying to pass existing object instances as parameters to the constructor of an object being created using the ObjectDatatProvider. This always fails with the given exception, even though my object has a constructor that takes one parameter:

开发者_运维知识库

System.Windows.Data Error: 34 : ObjectDataProvider cannot create object; Type='VegaViewModel'; Error='Wrong parameters for constructor.' MissingMethodException:'System.MissingMethodException: Constructor on type 'WpfApplication1.VegaViewModel' not found. at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Windows.Data.ObjectDataProvider.CreateObjectInstance(Exception& e)'

Here is my Xaml:

<ObjectDataProvider ObjectType="{x:Type WpfApplication1:VegaModel}" MethodName="Sample" x:Key="VegaPnlData"/>     
<ObjectDataProvider ObjectType="{x:Type WpfApplication1:VegaViewModel}" x:Key="VegaViewModel">
                <ObjectDataProvider.ConstructorParameters>
                    <ObjectDataProvider ObjectInstance="{StaticResource VegaPnlData}"/>
               </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>

If I use this xaml I get the same error as well:

 <ObjectDataProvider ObjectType="{x:Type WpfApplication1:VegaViewModel}" x:Key="VegaViewModel">
            <ObjectDataProvider.ConstructorParameters>
                <StaticResource ResourceKey="VegaPnlData"/>
            </ObjectDataProvider.ConstructorParameters>
        </ObjectDataProvider>

Here is the code for the VegaViewModel class:

public class VegaViewModel
{            
    public VegaViewModel(VegaModel vegaPnl)
    {
        VegaPnl = vegaPnl;           
    }

    public VegaModel VegaPnl { get; set; }            
}


You can't pass an ObjectDataProvider via the ConstructorParameters. The reason as Dr. WPF adequately states...

An ObjectDataProvider (ODP) is designed to be used with a Binding. If you use it outside of the context of a binding, you end up refering to an instance of the ODP rather than the dereferenced object that it "provides".

Your trying to do something the framework won't allow by design.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜