gpt4 book ai didi

c# - WPF 我没有在 Label 和 Texblock 之间绑定(bind)工作

转载 作者:行者123 更新时间:2023-12-03 10:42:00 35 4
gpt4 key购买 nike

我一直在尝试不同的方法,但没有运气。所以这是我的问题:我想将我在文本 block 上键入的内容绑定(bind)到标签。没什么特别的,但我想在此基础上构建其他东西。这是我的代码:

主窗口.Xaml

<StackPanel Orientation="Vertical">
<TextBox Text="{Binding Path=Name2, ElementName=window, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="{Binding Path=Name2, ElementName=window, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>

主窗口.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

private string _name2;

public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}

public MainWindow()
{
InitializeComponent();
}
}

我的期望是当我在文本 block 上键入时看到标签发生变化,我已经使用 Xamarin 完成了很多次,但我无法让它在 WPF 上工作。我错过了什么?

提前致谢。

最佳答案

为了使您的绑定(bind)工作,MainWindow房产 Name必须设置为“窗口”。

<Window ...
Name="window">

然后,在构造函数中,设置 DataContext :
public MainWindow()
{
InitializeComponent();
DataContext = this;
}

笔记:

但是,对于数据绑定(bind)和 MVVM说得通,你真的应该考虑使用 ViewModel并分开 View来自 ViewModel .

笔记2:

正如评论者所指出的,您不需要同时执行上述两项操作。两者中的任何一个都足够了。

关于c# - WPF 我没有在 Label 和 Texblock 之间绑定(bind)工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398924/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com