我试图实现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));
}
}
}
这是我的视图模型:
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>
它仍然无法正常工作。
绑定应指向FirstName属性。WPF无法自己弄清楚如何将Friend类转换为字符串。
Text="{Binding Friend.FirstName}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句