【发布时间】:2015-04-11 16:46:26
【问题描述】:
我正在将一个可观察的集合绑定到一个数据网格。通过异步调用从服务器获取的集合。集合模型包含一个名为“System.Windows.Media.Brush”类型的“BackgroundBrush”属性,该属性绑定到数据网格中模板列的背景颜色。 Brush 属性可以是 SolidColorBrush 或 LinearGradientBrush,具体取决于应用于该属性的业务逻辑。
在向数据网格呈现数据时,应用程序会抛出类似“必须在与 DependencyObject 相同的线程上创建 DependencySource”这样的异常。
调试问题时注意的事项
问题在于“背景”属性。注释掉这个属性绑定并使异步调用工作正常。
使服务调用同步可以正常工作,但我需要它作为异步调用。
在 Application.Current.Dispatcher.Invoke 中进行服务调用没有任何区别
以下是示例应用程序代码
型号
public class Model
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public Brush BackgroundBrush { get; set; }
}
查看模型
private ObservableCollection<Model> _dataCollection;
public ObservableCollection<Model> DataCollection
{
get { return _dataCollection; }
set
{
_dataCollection = value;
RaisePropertyChanged(() => DataCollection);
}
}
public RelayCommand LoadCommand { get; private set; }
private async Task LoadData()
{
var list = await Task.Run(() => GetData());
DataCollection = new ObservableCollection<Model>(list);
}
private ObservableCollection<Model> GetData()
{
return new ObservableCollection<Model>()
{
new Model()
{
Address = "a",
Email = "2",
Name = "3",
BackgroundBrush = new SolidColorBrush(Colors.SaddleBrown)
}
};
}
查看
<Grid x:Name="LayoutGrid">
<DataGrid ItemsSource="{Binding DataCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border Background="{Binding BackgroundBrush}">
<TextBlock Text="{Binding Name}"></TextBlock>
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
【问题讨论】:
-
不要将您的代码发布为图像。请改用正确的代码块。
标签: wpf xaml data-binding async-await mvvm-light