Reputation: 1009
I'm working on a project that is getting data from a backend, ie, the data is constantly changing dynamically, and the frontend shouldn't have to care. I need to expose this data to wpf such that someone can bind things to the data in wpf via expression blend. Readonly is fine. In short, how do I do databinding to the property Foostring in a instance of a class "foo" of type "Foo" if my flow of control is roughly the following:
public partial class Window1 : window
{
public Window1()
{
InitializeComponent();
Foo foo = new foo;
}
// my text box is defined in the xaml of this window.
}
public ref class Foo
{
Foo()
{
FooProperty = "work,dammit";
}
private string _foostring="";
public string FooProperty
{
get {return _foostring;}
set {foostring=value;}
}
}
I can get things to work if in the constructor of the Foo class I set binding on the text box, and if I inherit from INotifyPropertyChanged and raise an event on the setting of FooProperty. However, this does not expose this variable to expression blend--it's not really setting a datasource. I've tried to set the binding in xaml and it compiles but doesn't update. Any help would be greatly appreciated!
Upvotes: 1
Views: 2725
Reputation: 185300
[Answer by Rokujolady]
For posterity, I've posted the solution:
I was instancing the object foo from c# when I should have been instancing from xaml, because xaml was creating its own instance which was not being updated because I was updating the c# instantiated instance. Apparently you can't reference an object created in c# from xaml, but you can reference one created in xaml from c#. The code ended up like this:
XAML:
<Window.Resources>
<local:Foo x:Name "foo" x:Key="FooDataSource" d:IsDataSource="True"/>
...
</Window.Resources>
<Grid x:name="blah">
<Grid DataContext="{Binding Source={StaticResource FooDataSource}}">
<TextBlock x:Name="myText" Text="{Binding FooProperty, Mode=Default}"></TextBlock></Grid>
C# Code looked like this:
public partial class Window1:window
{
Foo myFooVariable = null;
public Window1()
{
InitializeComponent();
myFooVariable = this.Resources["FooDataSource"] as Foo;
myFooVariable.FooString = "Work, Dammit";
}
}
Upvotes: 1