XAML绑定BitmapImage ViewModel属性

30 wpf multithreading dispatcher bitmapimage

我从视图模型类更新列表框有问题.我使用Caliburn Micro框架.我的情况在这里:

我在listbox上绑定了bindableCollection类型的属性:

视图模型中的代码:

private BindableCollection<UserInfo> _friends;

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

在视图模型中,我创建假的服务方法,将新的新数据作为List返回,并使用此数据更新属性Friends,它们在listbox上绑定.

我每隔3秒就在调度员计时器滴答事件中调用假服务方法.

 private static UserInfo FakeUser()
        {
            var user = new UserInfo
            {
                Age = "16",
                Emphasis = true,
                IdUser = "11542",
                IsBlocked = false,
                IsFriend = true,
                LocationInfo = new Location
                {
                    CityName = "TN",
                    IdCity = 123456,
                    IdRegion = 1246,
                    RegionName = "TN",
                },
                StatusInfo = new Status
                {
                    IdChat = 12,
                    IsLogged = true,
                    LastLogin = "153151",
                    IsChating = true,
                    RoomName = "Car",
                },
                ProjectStatusInfo = new ProjectStatus(),
                IsIamFriend = true,
                PlusInfo = new Plus(),
                ProfilePhoto = new BitmapImage(new Uri("http://pokec.azet.sk/vanes90?i9=1f104a294997", UriKind.RelativeOrAbsolute))

            };

            return user;
        }

        private static IEnumerable<UserInfo> GetFakeFriends()
        {
            var list = new List<UserInfo>();

            for (int i = 0; i < 20; i++)
            {
                list.Add(FakeUser());
            }

            return list;
        }

        private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
        {
            if (_isExecuting)
                return;
            _isExecuting = true;
            new System.Threading.Tasks.Task(() =>
            {
                var freshFriends = GetFakeFriends();

                Execute.OnUIThread((System.Action)(() =>
                {
                    Friends.Clear();
                    foreach (var freshFriend in freshFriends)
                    {
                        Friends.Add(freshFriend);

                    }
                }));
            }).Start();

            _isExecuting = false;
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果我不在列表框上应用任何样式,它就可以正常工作.

视图:

<Grid>
    <ListBox Name="Friends"
             Grid.Row="2" 
             Margin="4,4,4,4">
    </ListBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)

如果我应用一些样式,我从列表框上的UserInfo绑定属性ProfilePhoto(typeof BitmapeImage).

风格在这里:

        <Style x:Key="friendsListStyle" TargetType="{x:Type ListBox}">
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid Name="RootLayout">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="0.3*"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="60"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Image Margin="4,4,4,2" Source="{Binding Path=ProfilePhoto}" Grid.Column="0"/>
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
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)

如果我在listbox/listbox项目上创建另一个样式,我只绑定字符串或bool属性,它运行良好.

我只有绑定bitmapImage属性才有问题.

BitmapImage属性为init:

ProfilePhoto = new BitmapImage(new Uri("http://pokec.azet.sk/vanes90?i9=1f104a294997", UriKind.RelativeOrAbsolute))
Run Code Online (Sandbox Code Playgroud)

URI是图片的url或文件的路径.

怎么了?感谢您的帮助和建议.

样式很好,只有当我不在另一个线程中使用方法调用刷新数据时它才有效.

Ken*_*art 71

如果您正在创建BitmapImage除UI线程之外的任何线程,那么这将解释此问题.您可以冻结BitmapImage以确保可以从任何线程访问它:

var bitmapImage = new BitmapImage(...);
bitmapImage.Freeze();
Run Code Online (Sandbox Code Playgroud)

  • 大!你是怎么发现的? (5认同)