Wpf 文本框不会定期更新
我创建了一个简单的.net核心wpf应用程序来表示我的问题。在主窗口上有一个文本框,应该通过绑定定期更新。但文本框只显示“Hello world”,而不显示时间 谢谢你的提示 MainWindow.xaml:Wpf 文本框不会定期更新,wpf,data-binding,Wpf,Data Binding,我创建了一个简单的.net核心wpf应用程序来表示我的问题。在主窗口上有一个文本框,应该通过绑定定期更新。但文本框只显示“Hello world”,而不显示时间 谢谢你的提示 MainWindow.xaml: <Window x:Class="WpfTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Text="{Binding Path=DebugText}" TextWrapping="Wrap" Margin="10,191,10,192"/>
</Grid>
</Window>
最好使用调度员。它的Tick事件在UI线程中触发,因此您不必使用Dispatcher。
公共类ViewModel:UserControl
看起来很奇怪。视图模型不应从视图类派生。是否调试程序以查看行DebugText=DateTime.Now.ToString()代码>是否执行过?并且:typeof(主窗口)
位于DependencyProperty中。寄存器错误。它必须是typeof(ViewModel)
。谢谢大家的帮助!
using System.Windows;
namespace WpfTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly ViewModel _viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = _viewModel;
}
}
}
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace WpfTest
{
public class ViewModel : UserControl
{
private Timer _updateTimer;
public ViewModel()
{
DebugText = "Hello world";
AutoResetEvent timerEvent = new AutoResetEvent(true);
_updateTimer = new Timer(OnTimer, timerEvent, 1000, 1000);
}
private void OnTimer(object stateInfo)
{
Application.Current.Dispatcher.Invoke(() =>
{
DebugText = DateTime.Now.ToString();
});
}
public string DebugText
{
get => (string)GetValue(DebugTextProperty);
set => SetValue(DebugTextProperty, value);
}
public static readonly DependencyProperty DebugTextProperty =
DependencyProperty.Register("DebugText",
typeof(string),
typeof(MainWindow),
new PropertyMetadata(null));
}
}