您必须设置DataContext
:
public MainWindow()
{
InitializeComponent();
SimpleText = "this is a test";
this.DataContext = this;
}
作为替代方案,您可以一边XAML这样的设置DataContext
:
XAML
<Window x:Class="TextBlockDontBind.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:this="clr-namespace:TextBlockDontBind"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<this:TestData />
</Window.DataContext>
<StackPanel>
<TextBlock Text="{Binding SimpleText}" Width="200"/>
</StackPanel>
</Window>
Code-behind
public class TestData
{
private string _simpleText = "this is a test";
public string SimpleText
{
get
{
return _simpleText;
}
set
{
_simpleText = value;
}
}
}
但是在这种情况下更新一个属性,对于一个Class必须实现INotifyPropertyChanged
接口。
谢谢!您也可以在文本分配之前设置DataContext。 – 4thSpace
在这个例子中进行扩展,你有什么想法为什么这个场景显示一个空白窗口:http://stackoverflow.com/questions/21767121/how-to-bind-to-collection-2-deep? DataContext现在已设置,但仍然没有。 – 4thSpace
@ 4thSpace:请参阅我的编辑,其中描述了设置'DataContext'的替代方法。好的,我看到了这个问题。 –