您必須設置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'的替代方法。好的,我看到了這個問題。 –