2009-07-17 104 views
2

我目前正在SilverLight 3應用程序上工作。我正在使用MVVM模式和棱鏡。除了下面的項目,我有一切工作。在我的一個觀點中,我必須使用OpenFileDialog。我試圖在ViewModel中這樣做,只是爲了找出SilverLight的安全模型禁止它,因爲它只允許用戶啓動。我已經將OpenFileDialog代碼移到了View的代碼隱藏中。雖然這是我的問題。雖然我已綁定到設置爲TwoWay的源,但它不會觸發ViewModel中屬性的setter。Silverlight MVVM Prism和OpenFileDialog

<Button x:Name="btnUpload" Height="20" Width="122" Canvas.Left="8" Canvas.Top="319" Content="Upload Image" Click="btnUpload_Click" /> 

Click事件:

<Image x:Name="imgCard" Height="283" Width="463" Canvas.Left="8" Canvas.Top="8" OpacityMask="White" Source="{Binding Path=CardImage, Mode=TwoWay}"/> 

按鈕由用戶使用:

private void btnUpload_Click(object sender, RoutedEventArgs e) 
     { 
      OpenFileDialog ofd = new OpenFileDialog(); 
      ofd.Filter = "PNG Files(*.png)|*.png"; 

      ofd.ShowDialog(); 
      using (Stream stream = ofd.File.OpenRead()) 
      { 
       BitmapImage image = new BitmapImage(); 
       image.SetSource(stream); 
       imgCard.Source = image; 
      } 
     } 

我的視圖模型正在實施INotifyPropertyChanged的,並具有以下

與結合圖像控制的示例屬性。

BitmapSource CardImage 
      { 
       get 
       { 
        return _imageSource; 
       } 
       set 
       { 
        _imageSource = value; 
        NotifyPropertyChanged("CardImage"); 
       } 
      } 

如果我在Setter上放置一個斷點。它從來沒有擊中它。

+0

什麼是您的XAML文件的DataContext? – 2009-07-17 17:56:08

+0

DataContext是ViewModel本身。它由Unity注入。 – cjibo 2009-07-17 18:19:51

回答

0

好吧,這是一個黑客,但它的工作原理。因爲我必須從UI中觸發OpenFileDialog,所以我可以直接將控件直接更新到DataContext來更新屬性。這工作,仍然呈現我所期望的用戶界面。

注意:HACK直到找到更好的方法。

private void btnUpload_Click(object sender, RoutedEventArgs e) 
     { 
      OpenFileDialog ofd = new OpenFileDialog(); 
      ofd.Filter = "PNG Files(*.png)|*.png"; 

      ofd.ShowDialog(); 
      using (Stream stream = ofd.File.OpenRead()) 
      { 
       BitmapImage image = new BitmapImage(); 
       image.SetSource(stream); 
       BitmapSource b = image; 

       //HACK: This works but now I'm tethered a bit. This updates the context property CardImage. 
       ((DesignerViewModel) this.DataContext).CardImage = b; 
       //imgCard.Source = b; 
      } 
     } 
1

至少在Silverlight 2中,我認爲以下規則可能會解釋爲什麼你會看到這種行爲。 「如果一個依賴屬性被綁定,並且在代碼中該屬性被顯式設置爲一個值,那麼該綁定將被刪除。」 (source

也許這已改變爲Silverlight 3?在那種情況下,我沒有任何建議。