即使在事件处理程序发生更新时触发了Property Changed,MVVM视图绑定也不会更新

时间:2017-11-29 10:14:56

标签: c# mvvm

我面临以下问题: 我使用一个类来封装串口操作,如下所示:

 public class SNScanner : IDisposable
{
    public string COMPort { get; set; }
    public int Baudrate { get; set; }
    SerialPort sp;
    string Rsv;
    public SNScanner(string cOMPort, int bauderate)
    {
        COMPort = cOMPort;
        Baudrate = bauderate;
        sp = new SerialPort()
        {
            PortName = COMPort,
            BaudRate = Baudrate,
            DataBits = 8,
            StopBits = StopBits.One,
            Parity = Parity.None
        };
        sp.DataReceived += Sp_DataReceived;
        if (!sp.IsOpen)
        {
            sp.Open();
        }
    }

    private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Thread.Sleep(100);
        Rsv = string.Empty;
        Rsv = sp.ReadExisting();
        if (!string.IsNullOrEmpty(Rsv) && Rsv.Length == 17 )
        {
            OnSerialNumberDetected(new SerialNumberDetectedEventArgs {
                SerialNumber = Rsv.Substring(1,15) });
        }
    }



    #region Serial number detected event
    public event EventHandler SerialNumberDetected;

    protected virtual void OnSerialNumberDetected(EventArgs e) => SerialNumberDetected?.Invoke(this, e);

    public void Dispose()
    {
        sp.Close();
        try
        {
            sp.Dispose();
        }
        catch (Exception)
        {

        }
    }


    #endregion
}
public class SerialNumberDetectedEventArgs : EventArgs
{
    public string SerialNumber { get; set; }
}

当它检测到符合我标准的正确序列号时,会触发onSerialNumberDetected事件。 在视图模型中,我将此事件替换为以下内容:

        myscanner = new SNScanner("COM3", 9600);
        SerialNumber = "Empty";
        myscanner .SerialNumberDetected += myscanner_SerialNumberDetected;

    }

    private void myscanner_SerialNumberDetected(object sender, EventArgs e)
    {
        SerialNumber = ((SerialNumberDetectedEventArgs)e).SerialNumber;
    }


    private string _sn;

    public string SerialNumber
    {
        get { return _sn; }
        set { _sn = value; NotifyPropertyChanged(nameof(_sn)); }
    }

我的视图绑定如下

<Window.DataContext>
    <local:mvm/>
</Window.DataContext>    
<Label FontFamily="Console"
                    FontSize="20"
                    Content="{Binding SerialNumber}"
                    Margin="5"
                    VerticalAlignment="Center"
                    Width="400"/>

在调试期间,视图模型可以从事件接收SerialNumber,但视图不会更新。

1 个答案:

答案 0 :(得分:1)

您正在通知错误的媒体名称:

    public string SerialNumber
    {
        get { return _sn; }
        set { _sn = value; NotifyPropertyChanged(nameof(_sn)); }
    }

而不是NotifyPropertyChanged(nameof(_sn))应该是NotifyPropertyChanged(nameof(SerialNumber));