在viewModel中的属性上绑定数据

本文关键字:绑定 数据 属性 viewModel | 更新日期: 2023-09-27 18:03:41

这个问题肯定已经讨论了几千次了,但我没有找到任何适合我需要的解决方案。我是SilverLIght的新手,我打算开始使用MVVM。因此,我做了以下视图模型:

public class MyViewModel 
    {
          private IRepository _Repository;
          public string CountText { get; set; }
          public MyViewModel (IRepository repository)
        {
            _Repository = repository;
            CountText = "test ctor";
        }
         public void MyButtonCommand()
        {
            _Repository.GetResult((Result r) => MyActionAsync(r), (Exception e) => ManageException(e));
        }
 public void MyActionAsync(SchedeConsunitiviResult result)
        {
            CountText = string.Format("{0} items", result.Count);
        }
        public void ManageException(Exception e)
        {
            //to log the exception here and display some alert message
        }
}

和这里的xaml:

<sdk:Label Content="{Binding Path=CountText, Mode=TwoWay}" Grid.Row="3" Height="28" HorizontalAlignment="Left" Margin="12,142,0,0" Name="label1" VerticalAlignment="Top" Width="120" Grid.ColumnSpan="2" />

CountText的第一个实例在Label中可见。但是async方法之后的第二个方法不会改变LAbel的内容。我是否应该添加一些像PropertyChanged这样的机制来告诉视图这个属性已经改变了?如果是这样,我怎么能只使用xaml ?

谢谢你的帮助

在viewModel中的属性上绑定数据

实现INotifyPropertyChanged,并通过EventHandler通知您的属性已更改

public class MyViewModel : INotifyPropertyChanged
{
    private string countText;
    public string CountText        
    {
        get { return this.countText; }
        set { this.countText = value; NotifyPropertyChanged("CountText"); }
    }
    .....snip.....
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(params string[] properties)
    {
        if (PropertyChanged != null)
        {
            foreach (string property in properties)
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
        }
    }
}

据我所知,您确实需要在视图模型中使用PropertyChanged之类的机制