0
我有一堆textboxes
我想绑定到我的viewmodel中的字符串。我以为我已经正确设置了所有内容,但是没有任何内容出现在文本框中。文本框没有正确绑定
这是我的XAML和我试图绑定的文本框之一。
<Window x:Class="Server.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:l="clr-namespace:Server"
xmlns:viewmodel="clr-namespace:Server.ViewModels"
Title="MainWindow">
<Window.DataContext>
<viewmodel:MainWindowViewModel />
</Window.DataContext>
<TextBlock Name="ShipLatTB"
FontSize="17"
Text="{Binding Path=CurrentShipLat, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
这里的视图模型:
namespace Server.ViewModels
{
class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _currentShipLat;
public string CurrentShipLat
{
get { return _currentShipLat; }
set { _currentShipLat = value; OnPropertyChanged("CurrentShipLat"); }
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
我测试设置,以确保数据实际上是在“_currentShipLat”这等于命令“测试”,和调试,以验证它。不知道还有什么错误?
注:该文本框应该能够动态更新。
编辑:如何给出downvote和投票结束的理由?这对任何人都没有帮助。
您是否在WPF窗口初始化后设置了字段_currentShipLat?这样WPF永远不会“看到”这个改变,因为它不会触发属性改变的事件。 要么确保在窗口初始化之前设置了字段,要么使用属性的setter而不是直接设置字段。 –
你可以发布你的TextBlock所在的xaml吗?我加载了你的解决方案,对我而言,这些值正确填充。 –
@NathanSwannet你是对的!我在初始化之后设置它,所以我必须使用setter属性。现在一切正常。如果你想把这个作为答案,我会标记它。 – pfinferno