[英]Binding to a property within an instance
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.
我需要将此数据公开给wpf,以便有人可以通过表达式blend将事物绑定到wpf中的数据。 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:
简而言之,如果我的控制流程大致如下,该如何在类型为“ Foo”的类“ foo”的实例中对属性Foostring进行数据绑定:
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. 如果在Foo类的构造函数中在文本框上设置绑定,并且继承自INotifyPropertyChanged并引发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.
我试图在xaml中设置绑定,它可以编译但不会更新。 Any help would be greatly appreciated!
任何帮助将不胜感激!
[Answer by Rokujolady] [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. 为了后代,我发布了解决方案:当我本应从xaml实例化时,我正在从c#实例化对象foo,因为xaml正在创建自己的实例,该实例由于更新c#实例化实例而未被更新。 Apparently you can't reference an object created in c# from xaml, but you can reference one created in xaml from c#.
显然,您不能引用从xaml在c#中创建的对象,但是可以引用从c#在xaml中创建的对象。 The code ended up like this: XAML:
代码最终如下所示: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: C#代码如下所示:
public partial class Window1:window
{
Foo myFooVariable = null;
public Window1()
{
InitializeComponent();
myFooVariable = this.Resources["FooDataSource"] as Foo;
myFooVariable.FooString = "Work, Dammit";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.