【发布时间】:2014-04-16 09:16:58
【问题描述】:
我正在尝试实现 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>
还是不行。
【问题讨论】:
-
您已将文本框绑定到
Friend- 您不想要Friend.FirstName吗?您需要告诉文本框要绑定到哪个属性 -
你能检查输出窗口吗?查看是否显示任何绑定错误?
-
@user3292642 你检查我的答案了吗?