必须在与DependencyObject相同的Thread上创建DependencySource

17 c# wpf dispatcher mvvm caliburn.micro

我将可观察字典从视图模型绑定到视图.我使用Caliburn Micro Framework.

视图:

    <ListBox Name="Friends" 
             SelectedIndex="{Binding Path=SelectedFriendsIndex,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             SelectedItem="{Binding Path=SelectedFriend, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
             Style="{DynamicResource friendsListStyle}"
             IsTextSearchEnabled="True" TextSearch.TextPath="Value.Nick"
             Grid.Row="2" 
             Margin="4,4,4,4"
             PreviewMouseRightButtonUp="ListBox_PreviewMouseRightButtonUp"
             PreviewMouseRightButtonDown="ListBox_PreviewMouseRightButtonDown" 
             MouseRightButtonDown="ListBox_MouseRightButtonDown"
             Micro:Message.Attach="[MouseDoubleClick]=[Action OpenChatScreen()]" >
Run Code Online (Sandbox Code Playgroud)

视图模型类中的代码.

属性看起来像这样:

public MyObservableDictionary<string, UserInfo> Friends
{
    get { return _friends; }
    set
    {
        _friends = value;
        NotifyOfPropertyChange(() => Friends);
    }
}
Run Code Online (Sandbox Code Playgroud)

在Dispatcher计时器中,我每隔3秒调用一个单独的线程新服务方法.

所以我的视图模型的构造函数我有这个:

        _dispatcherTimer = new DispatcherTimer();
        _dispatcherTimer.Tick += DispatcherTimer_Tick;
        _dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
        _dispatcherTimer.Start();

        _threadDispatcher = Dispatcher.CurrentDispatcher;
Run Code Online (Sandbox Code Playgroud)

而计时器滴答方法在这里:

    private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
    {
        new System.Threading.Tasks.Task(() =>
        {
            //get new data from server
            MyObservableDictionary<string, UserInfo> freshFriends = _service.GetFriends(Account);

            _threadDispatcher.BeginInvoke((System.Action)(() =>
            {
                //clear data, Friend is property which is binded on listobox control
                Friends.Clear();

                //here is problem - > refresh data
                foreach (var freshFriend in freshFriends)
                {
                    Friends.Add(freshFriend);

                }
            }));
        }).Start();
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,我收到此错误:

Must create DependencySource on same Thread as the DependencyObject.


   at System.Windows.Markup.XamlReader.RewrapException(Exception e, Uri baseUri)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Border.MeasureOverride(Size constraint)
Run Code Online (Sandbox Code Playgroud)

我尝试替换调度程序:

这个 _threadDispatcher = Dispatcher.CurrentDispatcher;

有了这个: _threadDispatcher = Application.Current.Dispatcher;

但它没有帮助.谢谢你的建议.

MyObservableDicionary不是依赖对象或具有依赖属性:

public class MyObservableDictionary<TKey, TValue> :
    IDictionary<TKey, TValue>,
    INotifyCollectionChanged,
    INotifyPropertyChanged
{..}
Run Code Online (Sandbox Code Playgroud)

小智 24

我遇到了类似的情况.

我将名为Person的类的ObservableCollection绑定到datagrid,Person.SkinColor是SolidColorBrush.

我做的是以下内容:

foreach (Person person in personData)
{
?PersonModel person= new Person( );
?......               
?personModel.SkinColor = new SolidColorBrush(person.FavoriteColor);
?personModel.SkinColor.Freeze();
?.....
}
Run Code Online (Sandbox Code Playgroud)

  • 我对 ImageSource 也有同样的问题。调用 Freeze() 在我的情况下也有效 (3认同)

rrh*_*tjr 20

只是一个猜测,但默认情况下,任务在后台线程上创建.尝试使用SynchronizationContext使用Task.Factory重载创建任务.我不确定在任务中使用Dispatcher是否按照预期的方式工作.

var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, uiContext);
Run Code Online (Sandbox Code Playgroud)

一旦这样做,您应该能够在不使用调度程序的情况下修改后备属性.


Bot*_*000 3

您的数据源是 DependencyObject 吗?如果是这样,它也需要在 UI 线程上创建。通常,您不需要从 DependencyObject 继承数据源。