【问题标题】:Wpf: The text block doesn't update after changeWpf:更改后文本块不更新
【发布时间】:2016-12-08 13:34:51
【问题描述】:

我有使用 MVVM 的 Wpf 应用程序,代码如下所示:

XAML:

<StackPanel Orientation="Vertical">
    <TextBox Text="{Binding DataFolder}" TextWrapping="Wrap"/>
    <Button Content="Convert" Padding="8" Command="{Binding ConvertCommand}" IsEnabled="True" MinWidth="220"/>
    <TextBlock Text="{Binding DoneMessage, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</StackPanel>

视图模型:

public class ConverterViewModel : NotificationObject
{
    public string DataFolder { get; set; }
    public string DoneMessage { get; set; }
    public DelegateCommand ConvertCommand { get; set; }

    private readonly List<BaseConverter> _converters = new List<BaseConverter>
    {
        new VisualCheckEventConverter()
    };

    public ConverterViewModel()
    {
        ConvertCommand = new DelegateCommand(VisualCheckEventConvertCommandExecute);
        DataFolder = ConfigurationManager.AppSettings["InputFolder"];
        DoneMessage = "Not done yet.";
    }

    private void VisualCheckEventConvertCommandExecute()
    {
        foreach (var c in _converters)
            c.Convert(DataFolder);
        DoneMessage = "Done!";
    }
}

当我运行应用程序时,消息“尚未完成”。显示,但在执行命令后,文本块的文本不会更新为“完成!”。

如何让它发挥作用?

【问题讨论】:

  • 从 INotifyProperyChanged 派生的 NotificationObject。
  • 它可能会实现它,从而允许使用 INotifyPropertyChanged 成员和函数,但您仍然必须显式触发通知

标签: wpf updatesourcetrigger


【解决方案1】:

如果您希望通知视图,您需要在 DoneMessage 属性设置器中使用 notifypropertychanged
此外,AFAIK 将 UpdateSourceTrigger=PropertyChanged 放在您的 TextBlock 上是没有意义的,因为它是只读的。如果您希望在文本更改时通知您的 ViewModel,您应该将它放在您的 TextBox 上。
应该是这样的:

    private string _doneMessage;

    public string DoneMessage
    {
        get { return _doneMessage; }
        set
        {
            _doneMessage = value;
            //the method name may vary based on the implementation of INotifyPropertyChanged
            NotifyPropertyChanged("DoneMessage");
        }
    }

【讨论】:

  • 我已经尝试过了,得到了以下错误:“名称 'NotifyPropertyChanged' 在当前上下文中不存在。”
  • 检查PropertyChanged 事件是如何在您的NotificationObject 类中调用的。或者只是发布课程
  • 我使用了 RaisePropertyChanged("DoneMessage");它有效。
  • 太好了,很高兴我能帮上一点忙。
猜你喜欢
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多