Winforms数据绑定和单声道INotifyPropertyChanged
我已经使我的第一个单声道应用程序运行在覆盆子pi上。问题是数据绑定没有更新UI。更具体地说,我的控制器/模型中的PropertyChanged事件为null。这意味着没有用户。Winforms数据绑定和单声道INotifyPropertyChanged
当我在Visual Studio调试器的windows上运行应用程序时,ui得到了正确更新。
单声道版本:4.6.2 OS:Raspbian喘息 .NET 4.5
我发现在该方案中没有太多的信息。由于它在windows和mono上工作,支持INotifyPropertyChanged接口,所以我认为它也可以在Linux上以单声道运行。
// creating the binding in code dhtControl.labelName.DataBindings.Add("Text", dht, "Name");
我觉得这是不需要其他的代码,因为它是默认的INotifyPropertyChanged的实现。唯一的区别是我将一个Action(control.Invoke)传递给模型以调用主线程上的更新。
问候
我有同样的问题,解决了加入由视图模型,其中更新所有的控制发射一个动作事件:
internal void InvokeUIControl(Action action)
{
// Call the provided action on the UI Thread using Control.Invoke() does not work in MONO
//this.Invoke(action);
// do it manually
this.lblTemp.Invoke(new Action(() => this.lblTemp.Text = ((MainViewModel)(((Delegate)(action)).Target)).Temperature));
this.lblTime.Invoke(new Action(() => this.lblTime.Text = ((MainViewModel)(((Delegate)(action)).Target)).Clock));
}
我注意到.NET和Mono和我之间的差异有同样的问题。比较.NET和Mono的源代码后,它首先出现的是,如果你想在ViewForm收到通知propertyName的任何Control.TextChanged你首先要在你的模型:
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler TextChanged;
protected void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
if (propertyName == "Text")
{
TextChanged?.Invoke(this, EventArgs.Empty);
}
}
}
事件处理程序被命名为“框TextChanged很重要“为了通知一个TextChanged。 然后仍然在你的模型,你可以设置:
private string _Text = "";
public string Text {
get {
return _Text;
}
set {
if (_Text != value) {
NotifyPropertyChanged ("Text");
}
}
}
而现在,在你看来,你可以做这样的事情。
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace EventStringTest
{
public partial class Form1 : Form
{
Model md = Model.Instance;
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", md, "Text", false
, DataSourceUpdateMode.OnPropertyChanged);
this.OnBindingContextChanged(EventArgs.Empty);
textBox1.TextChanged += (object sender, System.EventArgs e) => { };
}
private void Form1_Load(object sender, EventArgs evt)
{
md.PropertyChanged += (object s, PropertyChangedEventArgs e) => { };
// This is just to start make Text Changed in Model.
md.TimerGO();
}
}
}
这似乎很多代码,但我仍然在寻找一个更优雅的更好的解决方案。
你最终搞清楚了吗?我遇到了同样的问题。 – Kohanz
我发现在添加数据绑定时,他们没有使用Mono注册到PropertyChangedEvent,但他们使用.Net。仍然不知道为什么。 – soulsource