c# - INotifyPropertyChanged/绑定(bind)?

标签 c# wpf c#-4.0 win-universal-app

我正在尝试弄清楚如何从另一个线程更新我的主 UI(例如文本 block )。到目前为止,我能够做到的唯一方法是使用 Progress 对象。我遇到无法使用 Progress 对象的情况,最近有人指出我使用 MVVM/绑定(bind)方法。我看了一些视频并做了一些例子,但我似乎无法让它工作。

<TextBlock Name="txtblock1" Text="{Binding count}"></TextBlock>

这是我的错误

Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Runtime.WindowsRuntime.dll Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll

查看(代码隐藏)

public sealed partial class MainPage : Page 
{
    public MainPage()
    {
        this.InitializeComponent();
        ViewModelexample obj = new ViewModelexample();
        txtblock1.DataContext = obj;
        obj.Methodasync();
    }
}

View 模型

public class ViewModelexample : INotifyPropertyChanged
{
    public string count { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void onPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler !=null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    public async void Methodasync()
    {
        await Method();         
    }

    public Task Method()
    {
        return Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; i++)
            {
                Task.Delay(1000).Wait();
                Debug.WriteLine(i.ToString());
                count = i.ToString();
                onPropertyChanged(i.ToString());
            }
        });
    }
}

关于我可能做错了什么有什么想法吗?

谢谢

最佳答案

您的 count 属性需要能够通知它已更改

public class ViewModelexample : INotifyPropertyChanged
{    
    private string _count;
    public string count { 
        get { return _count; } 
        set {
            if(value != _count) {
                _count = value;
                OnPropertyChanged(nameof(count));
            }
        } 
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        // the new Null-conditional Operators are thread-safe:
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private int _testCount = 0;
    public void Method() {
        testCount++;
        Debug.WriteLine(testCount.ToString());
        count = testCount.ToString();
    }

}

上面的工作是因为新的 Null 条件运算符是 thread-safe :

Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. ... The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in a temporary variable.

要测试它,您可以编辑 ViewModel 方法并让 View 在页面加载或按钮单击等事件上调用它。

public sealed partial class MainPage : Page 
{
    ViewModelexample obj = null;
    public MainPage()
    {
        this.InitializeComponent();
        obj = new ViewModelexample();
        this.DataContext = obj;        
    }

    public void OnSomeEventHandler() {
        obj.Method();
    }
}

关于c# - INotifyPropertyChanged/绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324612/

相关文章:

c# - 大数组如何分配内存?

c# - 异步文件和文件夹复制 - C#

c# - Visual Studio 2010 卡在跟踪点上

asp.net - 如何使用 foreach 循环清除所有文本框?

wpf - 如果用户没有写权限,如何写入文件

c# - 为什么 C# 构造函数不能推断类型?

c# - LongListSelector 无法更改 ItemsSource

c# - 指定的元素已经是另一个元素的逻辑子元素。先断开它。在用户控制中

属性上的 WPF Storyboard触发器已更改

c# - 通过直接传递获取属性名称和类型