我有以下XAML:
<StackPanel Orientation="Vertical">
<TextBox IsReadOnly="True" Text="{Binding SchedulerStatus, Mode=OneWay}" Width="150" VerticalAlignment="Center" Margin="10" />
<Button Width="75" Height="30" Content="Test" Command="{Binding StartScheduler}" />
</StackPanel>
这是绑定到此视图模型的窗口:
public class SchedulerViewModel : ViewModelBase // ViewModelBase implements INotifyPropertyChanged, using the [CallerMemberName] attribute.
{
private readonly SchedulerServiceClient _proxy;
public SchedulerViewModel()
{
_proxy = new SchedulerServiceClient();
SchedulerStatusPoller poller = new SchedulerStatusPoller(this, _proxy);
}
private SchedulerStatus _schedulerStatus;
internal SchedulerStatus SchedulerStatus
{
get
{
return _schedulerStatus;
}
set
{
if (value != _schedulerStatus)
{
_schedulerStatus = value;
OnPropertyChanged();
}
}
}
}
SchedulerServiceClient
是持续运行的WCF服务的代理,并且具有我需要观察的Status
属性。因为我无法在两天后尝试从WCF获得回调,所以我实现了SchedulerStatusPoller
,定期轮询WCF状态,并更新viewmodel状态,希望更新WCF状态的显示。
class SchedulerStatusPoller
{
private static readonly Timer StatusTimer = new Timer(5000);
private static SchedulerViewModel viewModel;
private static SchedulerServiceClient proxy;
public SchedulerStatusPoller(SchedulerViewModel targetViewModel, SchedulerServiceClient proxy)
{
SchedulerStatusPoller.proxy = proxy;
viewModel = targetViewModel;
StatusTimer.Elapsed += StatusTimerElapsed;
StatusTimer.AutoReset = true;
StatusTimer.Enabled = true;
StatusTimer.Start();
}
void StatusTimerElapsed(object sender, ElapsedEventArgs e)
{
viewModel.SchedulerStatus = proxy.GetStatus();
}
}
我在UI(窗口)中直接使用了以下代码,确认PropertyChanged
正在引发SchedulerViewModel
。抛出异常。
void _viewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
throw new NotImplementedException();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
((SchedulerViewModel)DataContext).SchedulerStatus = SchedulerStatus.Processing;
}
轮询器每五秒调用一次viewmodel上的SchedulerStatus
属性,但文本框不会更新。我做错了什么?
答案 0 :(得分:0)
你必须提到源触发器
Text="{Binding SchedulerStatus, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
答案 1 :(得分:0)
Setter中的OnPropertyChanged缺少一个参数。不应该是......像
的PropertyChanged(&#34; SchedulerStatus&#34);
答案 2 :(得分:0)
也许,你可以像这样编码:
OnPropertyChanged(this,new PropertyChangedEventArgs(“SchedulerStatus”));