如何使依赖项属性静态化?

时间:2019-04-29 22:28:10

标签: c# wpf

我有一个名为xpos的依赖项属性,该属性具有绑定到文本框的功能。我能够在文本框中动态显示依赖项属性的值,而不会出现问题。但是我有一个arduino,我正在与之交谈。我使用另一个线程来读取任何传入的数据。在此线程中,一些数据可能会更改my依赖项属性。问题在于线程运行的函数是静态的,而依赖项属性不是静态的。我无法在此函数中调用该属性。

我尝试将属性设为静态,但是这导致了其他错误。

<TextBox Grid.Column="1" Grid.Row="0" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" VerticalAlignment="Center" Width="50" Margin="12.4,10,0,10" Name="Xdisplay" Text="{Binding xpos, ElementName=CurrentWindow}" IsReadOnly="True" TextChanged="Xdisplay_TextChanged"/>
Thread Readthread = new Thread(Read);
static public Boolean _continue = true;
static public 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("xpos", typeof(float), typeof(Window), new PropertyMetadata(null));

        public float xpos
        {
            get { return (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.Substring(0))
                        {
                            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) { }
            }
        }

1 个答案:

答案 0 :(得分:2)

依赖性并不是最好的选择,在WPF 4.5中,您可以bind directly to static properties代替:

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();
            }
        });
    }
}

更好的解决方案是完全删除静态属性,将所有内容放入常规类实例中,并使用依赖注入使其成为单例,但是上面的方法也可以使用。