Reputation: 53
I have a dependency property called xpos with binding to a textbox. I was able to dynamically display the value of my dependency property on the textbox with no problem. However I have an arduino which I am talking to serially. I use another thread to read any incoming data. In this thread some data that comes is suppose to change the my dependency property. The problem is that the function the thread runs is static and the dependency property is not static. I can't call the property in this function.
I tried to make the property static but that created other errors.
<TextBox Grid.Column="1" Grid.Row="0"
HorizontalAlignment="Left" VerticalAlignment="Center"
TextWrapping="Wrap"
Width="50" Height="20"
Margin="12.4,10,0,10"
Name="Xdisplay"
Text="{Binding xpos, ElementName=CurrentWindow}"
IsReadOnly="True"
TextChanged="Xdisplay_TextChanged"/>
Thread Readthread = new Thread(Read);
public static bool _continue = true;
public static SerialPort com;
com.BaudRate = Convert.ToInt32(Rates.Text);
com.PortName = Ports.
com.Open();
MessageBox.Show("Connection Successful");
Readthread.Start();
public static readonly DependencyProperty xposproperty =
DependencyProperty.Register(nameof(xpos), typeof(float), typeof(Window), new PropertyMetadata(null));
public float xpos
{
get => (float)GetValue(xposproperty);
set => SetValue(xposproperty, value);
}
public static void Read()
{
while (_continue)
try
{
string message = com.ReadLine();
if (message.Contains("max limit reached"))
{
MessageBox.Show(message);
switch (message)
{
case "x":
max = true;
xpos = int.Parse(message.Substring(20, message.Length));
break;
case "y":
ypos = int.Parse(message.Substring(20, message.Length));
break;
}
}
Console.WriteLine(message);
}
catch (TimeoutException)
{
}
}
Upvotes: 0
Views: 1119
Reputation: 16138
Dependency properties aren't the best thing for this, in WPF 4.5 you can bind directly to static properties instead:
public class MainViewModel : ViewModelBase
{
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
private static double _XPos;
public static double XPos
{
get { return _XPos; }
set
{
if (_XPos != value)
{
_XPos = value;
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("XPos"));
}
}
}
public MainViewModel()
{
// simulate values being read by the serial port
Task.Run(async () =>
{
var rng = new Random();
while (true)
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
XPos = rng.Next();
}
});
}
}
A better solution would be to drop the static properties altogether, put everything in a regular class instance and use dependency injection to make it a singleton, but the above will also work.
Upvotes: 2