【问题标题】:WPF Simple Binding to an objects propertyWPF 简单绑定到对象属性
【发布时间】:2023-06-09 06:03:01
【问题描述】:

我在 wpf/xaml 中的绑定有一些问题。有这个简单的文件:

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

我想将文本块的内容绑定到我的属性“MyText”。我的代码如下所示:

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

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

总而言之很简单,但是当我启动文本块时没有内容 - 怎么办?

【问题讨论】:

  • 更新:我什至没有在属性处获得断点

标签: wpf xaml binding


【解决方案1】:

您的绑定中需要一个元素名称:

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

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

【讨论】:

    【解决方案2】:

    如果我没记错我的 WPF 绑定语法,我相信你的绑定表达式应该是 Text="{Binding Path=MyText}"

    【讨论】:

    • 试过了,没有运气,还是空白... ...Text="{Binding Path=MyText}" />
    • 试过源代码,只是渲染了文本“MyText”,它是属性的名称......编辑:在绑定中具有名称的解决方案有效
    • 感谢您的复习,我学习WPF已经有一段时间了:)
    【解决方案3】:

    有很多方法可以做到这一点。对于这种简单的形式,最简单的可能是:

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

    【讨论】: