Metro UI 用の ImagePicker ユーザー コントロールを開発しています。その原理は単純です。画像を表示し、画像がタップされるとファイル ダイアログが開き、現在の画像を変更できるようになります。これを実現するために、ユーザー コントロールは、ラップされたイメージがバインドされる ImageSource プロパティを公開するだけです。
<local:ImagePicker Source="{Binding PictureUri, Mode=TwoWay}"/>
起動時にバインディングは正常に機能し、ビュー モデルによって提供される PictureUri プロパティから画像が表示されます。問題は、画像をタップして新しい画像を選択すると、新しい画像が表示されますが、TwoWay バインディング モードにもかかわらずビュー モデルでバインディング値が更新されないことです。この問題はユーザー コントロール コードに起因すると考えていますが、値が実際にラップされたイメージに伝達されたときに値がビュー モデルに伝達されない理由がわかりません...
ここに XAML 部分があります。
<UserControl x:Name="ImagePickerUserControl"
x:Class="ImageUserControl.ImagePicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="ImagePickerRootGrid" Background="Gray">
<Image Source="{Binding Source, ElementName=ImagePickerUserControl}"/>
</Grid>
</UserControl>
そして、コードの部分、長くて申し訳ありませんが、ここではすべてが重要だと思います.
public sealed partial class ImagePicker : UserControl
{
public ImagePicker()
{
this.InitializeComponent();
// Hookup event to handle when the control is tapped
this.Tapped += ImagePicker_Tapped;
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImagePicker),
new PropertyMetadata(null, new PropertyChangedCallback(ImagePicker.OnSourceChanged)));
public ImageSource Source
{
get
{
return (ImageSource)this.GetValue(ImagePicker.SourceProperty);
}
set
{
this.SetValue(ImagePicker.SourceProperty, value);
}
}
private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Update Visual State
}
private async void ImagePicker_Tapped(object sender, TappedRoutedEventArgs e)
{
// Pick up a new picture
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".jpg");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".png");
var pngFile = await filePicker.PickSingleFileAsync();
// If the user picked up a file
if (pngFile != null)
{
BitmapImage bitmap = new BitmapImage();
await bitmap.SetSourceAsync(await pngFile.OpenReadAsync());
// Update the source image
this.Source = bitmap;
}
}
}
この問題は私の間違いだと思いますが、ここで何が起こっているのか理解できません。プロジェクトを実行してコードをよりよく理解したい場合は、SkyDrive にアップロードして共有しました: ImageUserControl
このような長い投稿をお読みいただき、ありがとうございます。