WPF Simple Binding to an objects property

我的未来我决定 提交于 2019-12-12 20:14:51

问题


Im having some problems with binding in wpf/xaml. Have this simple file:

<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>

Where i want to bind the content of the textblock to my property "MyText". My code looks like this:

 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        public string MyText
        {
            get { return "This is a test"; }
        }
    }

All in all very simple, but when i start the textblock has no content - howcome?


回答1:


you need an element name in your binding:

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

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



回答2:


If I'm remembering my WPF binding syntax correctly, I believe your binding expression should read Text="{Binding Path=MyText}"




回答3:


There are a number of ways to accomplish this. Probably the easiest for something as simple as this form is:

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


来源:https://stackoverflow.com/questions/1462231/wpf-simple-binding-to-an-objects-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!