我正在尝试使用INotifyPropertyChanged
和串口。
出于某种原因,我总是将财产变更归零,我不明白为什么。为什么会发生这种情况,我该怎么办呢?
Xaml代码:
<Label Grid.Column="1" x:Name="lblStatus"
Content="{Binding Path = SerialPortOpenStatus, UpdateSourceTrigger = PropertyChanged,
Converter = {StaticResource CComPortStatusTextCovertor}}"></Label>
C#代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private SerialPort sp;
private bool _SerialPortOpenStatus;
public bool SerialPortOpenStatus
{
get { return _SerialPortOpenStatus; }
set {
_SerialPortOpenStatus = value;
OnPropertyChanged("SerialPortOpenStatus");
}
}
public MainWindow()
{
InitializeComponent();
sp = new SerialPort();
this.DataContext = this;
lblStatus.DataContext = sp;
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(CheckSerialPort));
t.IsBackground = true;
t.Start();
}
private void btnReset_Click(object sender, RoutedEventArgs e)
{
}
private void CheckSerialPort()
{
while (true)
{
if (sp != null)
{
_SerialPortOpenStatus = sp.IsOpen;
}
System.Threading.Thread.Sleep(500);
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void OnPropertyChanged( string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}