WPF简单绑定到对象属性

问题描述:

Im在wpf/xaml中绑定有一些问题。有这个简单的文件:WPF简单绑定到对象属性

<Window x:Class="test.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <Grid> 
     <TextBlock Height="21" Foreground="Black" Margin="74,98,84,0" Name="textBlock1" VerticalAlignment="Top" Text="{Binding MyText}" /> 
    </Grid> 
</Window> 

我在哪里要将textblock的内容绑定到我的属性“MyText”。我的代码看起来像这样:

​​

总而言之非常简单,但是当我启动textblock时没有内容 - howcome?

+0

更新:我不甚至在酒店 – H4mm3rHead 2009-09-22 20:00:10

在你需要绑定元素名称:

<Window ... x:Name="ThisWindow"...> 

     <TextBlock ... Text="{Binding MyText, ElementName=ThisWindow}" /> 

如果我记得正确我的WPF绑定语法,我相信你的绑定表达式应该阅读的文本=“{绑定路径= MYTEXT}”

+0

试过,没有运气,还是空白...... ...文本=“{结合得到一个断点路径= MYTEXT}” /> – H4mm3rHead 2009-09-22 19:59:07

+0

试过源,只是呈现的文字‘MYTEXT’,这是该属性的名称... 编辑:在绑定工作 – H4mm3rHead 2009-09-22 20:09:16

+0

感谢您的复习与一个名字解决方案,它已经有一段时间自从我学习WPF :) – jturinetti 2009-09-22 20:34:16

有许多方法可以实现这一点。也许最简单的是这种形式简单的东西是:

public Window1() 
{ 
    InitializeComponent(); 
    this.DataContext = this; 
}