gpt4 book ai didi

c# - 访问DependencyProperty : The calling thread cannot access this object because a different thread owns it

转载 作者:行者123 更新时间:2023-12-03 13:17:00 30 4
gpt4 key购买 nike

当DependencyProperty值更改时,我想将数据加载到WPF DataGrid中。我以为这样简单就可以了,但没有用。

public SQLiteDb.Attorney attorney
{
get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
set {
SetValue(attorneyProperty, value);
GetAttorneysIdentitiesAsync(); //Load the data here.
}
}
public static readonly DependencyProperty attorneyProperty =
DependencyProperty.Register("attorney", typeof(SQLiteDb.Attorney),
typeof(AttorneyDetails), new PropertyMetadata(new SQLiteDb.Attorney()));

但是我最终遇到了很少有经验的线程异常。方法 GetAttorneysIdentitiesAsync看起来像这样,我想它正在尝试从另一个线程访问属性值。
public async void GetAttorneysIdentitiesAsync()
{
AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>().Where(x => x.AttorneyId == attorney.Id).ThenBy(x => x.Id).Take(30).ToListAsync();
AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}

每当我尝试从属性类中访问属性时,都会得到异常。
The calling thread cannot access this object because a different thread owns it.

最佳答案

您应该在任务线程外部访问attorny属性:

public async Task GetAttorneysIdentitiesAsync()
{
var id = attorney.Id;

AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>()
.Where(x => x.AttorneyId == id)
.ThenBy(x => x.Id)
.Take(30)
.ToListAsync();

AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}

还要注意,在依赖项属性的CLR包装器中,除了GetValue和SetValue之外,您不应调用其他任何东西。原因解释为 here

您应该像这样注册一个PropertyChangedCallback:
public SQLiteDb.Attorney attorney
{
get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
set { SetValue(attorneyProperty, value); }
}

public static readonly DependencyProperty attorneyProperty = DependencyProperty.Register(
nameof(attorney), typeof(SQLiteDb.Attorney), typeof(AttorneyDetails),
new PropertyMetadata(new SQLiteDb.Attorney(), attorneyPropertyChanged));

private static async void attorneyPropertyChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e)
{
await ((AttorneyDetails)o).GetAttorneysIdentitiesAsync();
}

关于c# - 访问DependencyProperty : The calling thread cannot access this object because a different thread owns it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47270750/

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