我正在尝试通过从 viewmodel.cs 启动来动态更新 xaml 程序上的绑定 由于某种原因,我无法在我的 CS 中的 label.content 上显示绑定: 每次运行时,要么我得到在 ViewModel 构造函数中设置但不会动态更新的默认值,要么当我注释掉构造函数中的值时,它仍然为空。
Xaml
<local:MainWindowViewModel/>
</Window.DataContext>
...
<Label x:Name="lblStatus" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="10,0,0,10" Content="{Binding UpdateStatusTxt}"/>
MainWindow.xaml.cs:
private MainWindowViewModel _viewModel;
public MainWindow()
{
InitializeComponent();
_viewModel = new MainWindowViewModel();
_viewModel.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "UpdateStatusTxt")
{
Dispatcher.Invoke(() => lblStatus.Content = _viewModel.UpdateStatusTxt);
}
};
DataContext = _viewModel;
}
视图模型:
ublic class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public MainWindowViewModel()
{
//StatusMessage = new RelayCommand(UpdateStatusTxt);
// Initialize CurrentMasterProducts
CurrentMasterProducts = new List<clsProductData>();
CurrentMasterAliases = new List<clsProductAlias>();
ImportMasterProducts = new List<clsProductAlias>();
ImportNAData = new List<clsProductData>();
ImportFullData = new List<clsProductData>();
ImportNotFoundData = new List<clsProductData>();
ImportNativeData = new List<clsProductData>();
ImportExpandedUPCData = new List<clsProductData>();
ImportAliasFoundData = new List<clsProductData>();
//UpdateStatusTxt = "Idle...";
}
...
private string _updateStatusTxt;
public string UpdateStatusTxt
{
get
{
return _updateStatusTxt;
}
set
{
if (_updateStatusTxt != value)
{
_updateStatusTxt = value;
OnPropertyChanged();
// OnPropertyChanged(nameof(UpdateStatusTxt)); //notify the binding
}
}
}
...
public static bool LoadMasterProducts(string FileToUse, MainWindowViewModel _viewModel)
{
try
{
_viewModel.UpdateStatusTxt = "Importing Master Products...";
_viewModel.WaitTask();
using (var tmpFileReader = new StreamReader(FileToUse))
{
// Skip the header row
tmpFileReader.ReadLine();
...
请注意,我已经使用示例中注释的 OnPropertyChanged() 以及未注释的行进行了尝试。
我已经尝试了如上所示的各种代码形式,并带有注释掉的代码。
您的
MainWindow
的构造函数不需要以下内容:
_viewModel.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "UpdateStatusTxt")
{
Dispatcher.Invoke(() => lblStatus.Content = _viewModel.UpdateStatusTxt);
}
};
当
Content
更改时,您尝试手动更新标签的 UpdateStatusTxt
;标签的绑定机制会自动处理这个问题。
您只需要在构造函数中添加以下内容:
private MainWindowViewModel _viewModel;
public MainWindow()
{
InitializeComponent();
_viewModel = new MainWindowViewModel();
DataContext = _viewModel;
}
就
UpdateStatusTxt
而言,您的视图模型看起来不错。不过,您没有显示更新它的代码。看起来 LoadMasterProducts
会这样做,但你没有解释何时调用它。