我有一堆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}" />
这是viewmodel:
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));
}
}
}
我通过在命令中将数据设置为“test”来测试确保数据实际上在'_currentShipLat'中,并进行调试以验证它。不确定还有什么问题?
注意:此文本框应该能够动态更新。
编辑:如何给出downvote和投票结束的理由?这对任何人都没有帮助。
答案 0 :(得分:1)
确保在初始化WPF窗口之前设置字段_currentShipLat。
如果在初始化窗口后执行此操作,WPF将永远不会看到&#39;此更改,因为它不会触发属性更改事件。要么确保在初始化窗口之前设置了字段,要么使用属性的setter而不是直接设置字段。