gpt4 book ai didi

wpf - WPF 数据绑定(bind)是否会将更改编码到 UI 线程?

转载 作者:行者123 更新时间:2023-12-03 14:56:08 25 4
gpt4 key购买 nike

我刚刚注意到在我的 ViewModel 中更改绑定(bind)属性时(MVVM)来自后台工作线程我没有得到任何异常并且 View 已正确更新。这是否意味着我可以安全地依赖 wpf 数据绑定(bind)编码 ViewModel 中的所有更改?到 UI 线程?我想我在某处读到应该确保(在 ViewModel 中)INotifyPropertyChanged.PropertyChanged在 UI 线程上触发。这在 3.5 中是否发生了变化?

最佳答案

是的标量,没有集合。对于集合,您需要一个专门的集合来为您编码,或者通过 Dispatcher 自己手动编码到 UI 线程。 .

你可能读过 INotifyCollectionChanged.CollectionChanged必须在 UI 线程上触发,因为 INotifyPropertyChanged.PropertyChanged 根本不正确.下面是一个非常简单的示例,它为您证明 WPF 编码属性更改。

Window1.xaml.cs:

using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace WpfApplication1
{
public partial class Window1 : Window
{
private CustomerViewModel _customerViewModel;

public Window1()
{
InitializeComponent();
_customerViewModel = new CustomerViewModel();
DataContext = _customerViewModel;

var thread = new Thread((ThreadStart)delegate
{
while (true)
{
Thread.Sleep(2000);
//look ma - no marshalling!
_customerViewModel.Name += "Appended";
_customerViewModel.Address.Line1 += "Appended";
}
});

thread.Start();
}
}

public abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;

if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class CustomerViewModel : ViewModel
{
private string _name;
private AddressViewModel _address = new AddressViewModel();

public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}

public AddressViewModel Address
{
get { return _address; }
}
}

public class AddressViewModel : ViewModel
{
private string _line1;

public string Line1
{
get { return _line1; }
set
{
if (_line1 != value)
{
_line1 = value;
OnPropertyChanged("Line1");
}
}
}
}
}

Window1.xaml:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBox Text="{Binding Name}"/>
<TextBox Text="{Binding Address.Line1}"/>
</StackPanel>
</Window>

关于wpf - WPF 数据绑定(bind)是否会将更改编码到 UI 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1321423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com