【问题标题】:call event when scale value changed缩放值更改时调用事件
【发布时间】:2018-05-26 20:34:53
【问题描述】:

我正在使用 UI 页面来表示秤的重量值。
c# 代码不断从真实刻度设备中读取刻度值
我必须向 UI(wpf) 屏幕显示价值。

当比例值改变时 UI 屏幕(scaleShow.xaml.cs) 需要知道 比例值已更改。

所以我正在考虑使用该事件让 scaleShow.xaml.cs 页面知道。
但不知道如何实现它

MainWindow.xaml.cs
    this.Dispatcher.BeginInvoke(new Action(delegate()
    {
        this.ctTbWeight.Text = this.curWeight + " kg";
        //when this.curWeight value changed I want to the scale.xaml.cs page notice it 
    }




scale.xaml.cs
     public scale(EventHandler handler, ILog logger, ObservableDictionary<string, LanguageChangedImpl> language, Stopwatch elapse)
            {
                InitializeComponent();


                this.Loaded += new RoutedEventHandler(_PageLoaded);

                this.tel = new Telegram();
                this.tel.Name = this.GetType().Name;
                this.pagingMachine = handler;
                this.def = new Defines();
                this.log = logger;
                this.lang = language;
                this.elapseTime = elapse;
            }

我尝试在 MainWindow.cs 中创建事件,但不确定如何使用它(如果它的按钮单击它很明显可以使用)

public event EventHandler getWeight;
        protected virtual void OngetWeight(EventArgs e)
        {
            EventHandler handler = getWeight;
            if (handler != null)
            {
                handler(this, e);
            }
        }

请给我一些指导,让缩放页面注意到缩放值已更改。如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: c# events delegates


    【解决方案1】:

    使用事件处理程序:

    公共事件EventHandler myEvent;

    public MainWindow()
    {
     InitializeComponent();
     myEvent = OnMyEvent;
    }
    
    private void OnMyEvent(object sender, EventArgs e)
    {
     //do UI updates
    }
    

    现在在您检查比例值的循环中,通过调用触发事件

    myEvent?.Invoke(this,null)
    

    【讨论】:

    • 实际上,一种更加面向对象的方式是创建一个 ScaleMeasure 对象来处理值的读取。它会有一个事件,例如 OnScaleValueChange。 MainWindow 将订阅此事件并使用它来触发 UI 更新。
    【解决方案2】:

    您可以在显示控件上使用 Dependency 属性和 Binding,而不是使用事件。 在后面的代码中,创建一个依赖属性:

    public static readonly DependencyProperty ScaleValueProperty = DependencyProperty.Register("ScaleValue", typeof(double), typeof(MainWindow), new PropertyMetadata(default(double)));
    
    public double ScaleValue { get { return (double) GetValue(ScaleValueProperty); } set { SetValue(ScaleValueProperty, value); } }
    

    注意:我假设该值是双倍的 - 如果您的值是其他值,请更改此值。 在 UI 的 xaml 文件中,只需将适当的属性绑定到 ScaleValue

    Text = {Binding ScaleValue}
    

    当 ScaleValue 改变时,正常的依赖属性通知事件应该处理 UI 的更新

    【讨论】:

    • 这种情况下可以使用事件吗?>
    • 当然可以。请参阅以下答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多