DataBinding Image.Source到PhotoChooserTask结果无法正常工作

时间:2012-04-21 00:20:59

标签: silverlight data-binding windows-phone

我有以下课程:

public class Sticky : INotifyPropertyChanged {

    // ... some members

    private BitmapImage _frontPic;
    [DataMember]
    public BitmapImage FrontPic {
        get {
            return _frontPic;
        }
        set {
            _frontPic = value;
            Changed("FrontPic");
            Changed("FrontBrush");
        }
    }
}

我正在尝试将其数据绑定到此XAML:

<Image Width="173" Height="173" Source="{Binding FrontPic}" />

在我的PhoneApplicationPage中使用此代码启动PhotoChooserTask之后:

public Sticky Sticky { get; set; }

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
    Sticky = new Sticky();
    DataContext = Sticky;
}

private void ShowFrontPicPicker(object sender, RoutedEventArgs e) {
    var t = new PhotoChooserTask();
    t.PixelHeight = 173;
    t.PixelWidth = 173;
    t.ShowCamera = true;

    t.Completed += (s, ev) => {
        if (ev.TaskResult == TaskResult.OK) {
            var img = new BitmapImage();
            img.SetSource(ev.ChosenPhoto);
            Sticky.FrontPic = img;
        }
    };

    t.Show();
}

但是,我的图片仍为空白。如果我将Image.Source属性直接分配给Image而不进行数据绑定,那么一切正常。数据绑定其他属性有效,它只是图像似乎是问题。如何使图像上的DataBinding有效?

1 个答案:

答案 0 :(得分:0)

发现问题了! PhotoChooserTask的完整回调不会在UI线程中执行,因此必须添加对Dispatcher.BeginInvoke的调用:

t.Completed += (s, ev) => Dispatcher.BeginInvoke(() => {
    // do stuff...
});