gpt4 book ai didi

WPF MVVM 数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:59:19 24 4
gpt4 key购买 nike

我试图实现 MVVM 模式,我只想拥有一个在启动时显示一些初始文本的 TextBox。

这是我的观点:(暂时不关心按钮和列表框)

<Window x:Class="Friends.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Width="150" Text="{Binding Friend}"></TextBox>
<ListBox Grid.Row="1" Width="150"></ListBox>
<Button Grid.Row="2" Content="Previous" Width="150"></Button>
<Button Grid.Row="3" Content="Next" Width="150"></Button>
</Grid>

这是我的模型:
public class FriendsModel : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
public FriendsModel(string _initialName)
{
_firstName = _initialName;
}

public event PropertyChangedEventHandler PropertyChanged;

public void RaisePropertyChanged(string _newName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(_newName));
}
}
}

这是我的 View 模型:
public class FriendsViewModel
{
public FriendsModel Friend { get; set; }
public FriendsViewModel()
{
Friend = new FriendsModel("Paul");
}

}

在我后面的代码中:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new FriendsViewModel();
}
}

我的项目正在构建没有任何错误,但它没有在我的文本框中显示文本。谁能帮我?

提前致谢

编辑:

我把它改成
<TextBox Grid.Row="0" Width="150" Text="{Binding Friend.Firstname}"></TextBox>

它仍然无法正常工作。

最佳答案

绑定(bind)应指向 FirstName 属性。 WPF 自己无法弄清楚如何将 Friend 类转换为字符串。

Text="{Binding Friend.FirstName}"

关于WPF MVVM 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23105007/

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