views:

1335

answers:

1

I cannot believe that nobody has gotten across this or perhaps I'm just missing something.

I've got a custom DataSourceController which handles retrieving data and providing it to the rest of the application controls. Naturally, it uses sql connection which I also initialize.

My App code:

private ISQLConnection conn;
public ISQLConnection SqlConnection { get { return conn; } }

private DataSourceController dataSource;
public DataSourceController DataSource { get { return dataSource; } }

protected override void OnStartup(StartupEventArgs e) {
    //-------------------------------------------------------
    // Initialize connections
    conn = new OracleSQLConnection("connectionStringHere");

    //-------------------------------------------------------
    // Initialize controllers
    //dataSource = new DataSourceController(conn);

    base.OnStartup(e);
}

Now I want to create ObjectDataProvider in XAML and then use it for binding data in controls:

<ObjectDataProvider ObjectType="{x:Type data:DataSourceController}" x:Key="DataSource" MethodName="GetVenues" />

The problem is that the DataSourceController does not have a parameterless constructor and requires an OracleSQLConnection object to be passed in (which is a public property in my App code-behind).

Is this at all possible? Or I have to resort to using in-code DataContext property for each control I want to data-bind?!

+2  A: 

You can add the DataSourceController as a resource (you'll have to do this from code-behind if you don't have a parameterless constructor) and use the ObjectDataProvider.ObjectInstance property to get the DataSourceController instance, then you can execute methods on it:

private ISQLConnection conn;
public ISQLConnection SqlConnection { get { return conn; } }

private DataSourceController dataSource;
public DataSourceController DataSource { get { return dataSource; } }

protected override void OnStartup(StartupEventArgs e) {
   //-------------------------------------------------------
   // Initialize connections
   conn = new OracleSQLConnection("connectionStringHere");

   //-------------------------------------------------------
   // Initialize controllers
   dataSource = new DataSourceController(conn);
   this.Resources.Add("myDataController", dataSource);
   base.OnStartup(e);
}

ObjectInstance can take a resource:

<ObjectDataProvider ObjectInstance="{StaticResource myDataController}" x:Key="DataSource" MethodName="GetVenues" />

There might be issues if your ObjectDataProvider is in App.xaml where it could be parsed before the DataSourceController resource is added, in which case you'd get an error because the "myDataController" resources wouldn't exist yet.

Robert Macnee
Thanks Robert! I tried this and it worked! Although I then had some (unrelated) problems further down the road and had to opt out for in-code init and then setting the object as DataContext of my window.
Alexandra