2016-04-15 107 views
2

我可以選擇在我的應用程序中添加新的客戶。客戶使用其ID,名稱和徽標存儲在數據庫中。標誌只是圖像文件的字符串(如logo.png)圖像被保存,但不會加載

標誌的添加看起來很好。當我選擇一個圖像時,它顯示在CustomerAddView中。

添加Customer後,CustomerAddView窗口關閉。客戶是在數據庫中創建的,數據庫中的徽標值是正確的。
刷新主窗口中的客戶列表(CustomerListView)。其他客戶的徽標工作正常。但新客戶的徽標(添加了AddView窗口)拋出這樣的警告:

System.Windows.Data Warning: 6 : 'DynamicValueConverter' converter failed to convert value '../../Media/Images/Logos/testlogo.png' (type 'String'); fallback value will be used, if available. BindingExpression:Path=Logo; DataItem='Customer_5A59789E69DE0B010CE32D4E23A696EDB09551158A85050E8CA80E51475D369B' (HashCode=45868004); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource') IOException:'System.IO.IOException: Kan bron media/images/logos/testlogo.png niet vinden. 
    bij MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access) 
    bij System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access) 
    bij System.IO.Packaging.PackWebResponse.CachedResponse.GetResponseStream() 
    bij System.IO.Packaging.PackWebResponse.GetResponseStream() 
    bij System.IO.Packaging.PackWebResponse.get_ContentType() 
    bij System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(Uri uri, Stream stream, BitmapCacheOption cacheOption, Guid& clsId, Boolean& isOriginalWritable, Stream& uriStream, UnmanagedMemoryStream& unmanagedMemoryStream, SafeFileHandle& safeFilehandle) 
    bij System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, Boolean insertInDecoderCache) 
    bij System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy) 
    bij System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) 
    bij MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) 
    bij MS.Internal.Data.TargetDefaultValueConverter.Convert(Object o, Type type, Object parameter, CultureInfo culture) 
    bij MS.Internal.Data.DynamicValueConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture) 
    bij System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)' 
System.Windows.Data Error: 11 : Fallback value 'Default' (type 'String') cannot be converted for use in 'Source' (type 'ImageSource'). BindingExpression:Path=Logo; DataItem='Customer_5A59789E69DE0B010CE32D4E23A696EDB09551158A85050E8CA80E51475D369B' (HashCode=45868004); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource') NullReferenceException:'System.NullReferenceException: De objectverwijzing is niet op een exemplaar van een object ingesteld. 
    bij System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) 
    bij System.Windows.Data.BindingExpressionBase.ConvertValue(Object value, DependencyProperty dp, Exception& e)' 

我想知道爲什麼我的標誌形象出現在文件管理器,在指定的文件夾,但不顯示在客戶列表中,因爲它應該。
我想知道爲什麼當通過Visual Studio的解決方案資源管理器添加圖像時工作正常,但是當我通過CustomerAddView(模型)將它們添加到同一文件夾時不起作用。

這裏的文件添加一個新的客戶: CustomerAddView:

<Grid Margin="5"> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 

     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="auto" /> 
      <ColumnDefinition Width="auto" /> 
      <ColumnDefinition Width="100" /> 
      <ColumnDefinition Width="100" /> 
     </Grid.ColumnDefinitions> 

     <TextBlock Name="TBCustomerTitle" FontWeight="Bold">Customer name:</TextBlock> 
     <TextBlock Grid.Column="1" FontWeight="Bold" Margin="5,0">*</TextBlock> 
     <TextBox Name="TBCustomerData" Grid.Column="2" Grid.ColumnSpan="2" 
       Text="{Binding NewCustomer.Name, UpdateSourceTrigger=PropertyChanged}"></TextBox> 

     <TextBlock Grid.Row="1" FontWeight="Bold">Customer logo:</TextBlock> 
     <Image Grid.Row="1" Grid.Column="2" MaxHeight="100" MaxWidth="100" 
       Source="{Binding NewCustomerLogo, UpdateSourceTrigger=PropertyChanged}" /> 
     <Button Grid.Row="1" Grid.Column="3" Content="Choose logo" 
       Command="{Binding SelectLogoCommand}"/> 

     <TextBlock Margin="0,10" Grid.Row="2" Grid.ColumnSpan="4">Fields marked with * are required fields.</TextBlock> 

     <Button Grid.Row="3" Grid.ColumnSpan="4" Margin="0,50,0,0" 
       Command="{Binding AddConfirmCommand}">Add this customer</Button> 
    </Grid> 

CustomerAddViewModel:

class CustomerAddViewModel : INotifyPropertyChanged 
    { 
     private RelayCommand addConfirmCommand; 
     private RelayCommand selectLogoCommand; 
     Image customerLogo; 
     string logoDirectory = "../../Media/Images/Logos/"; 
     DBCustomer dbCustomer = new DBCustomer(); 

     #region Add Customer 
     public ICommand AddConfirmCommand 
     { 
      get { return addConfirmCommand ?? (addConfirmCommand = new RelayCommand(() => AddConfirmCustomer())); } 
     } 

     private void AddConfirmCustomer() 
     { 
      if(newCustomer.Logo != null) 
      {     
       customerLogo.Save(logoDirectory + newCustomer.Logo);     
      } 
      else 
      { 
       newCustomer.Logo = "Default.png"; 
      } 
      if (!dbCustomer.Create(newCustomer)) 
      { 
       return; 
      } 
      App.Messenger.NotifyColleagues("AddCustomerDone"); 
     } 
     #endregion 

     #region Add logo 
     public ICommand SelectLogoCommand 
     { 
      get { return selectLogoCommand ?? (selectLogoCommand = new RelayCommand(() => SelectLogo())); } 
     } 

     private void SelectLogo() 
     { 
      OpenFileDialog chooseFile = new OpenFileDialog(); 
      chooseFile.Title = "Select a logo"; 
      chooseFile.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" + 
       "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + 
       "Portable Network Graphic (*.png)|*.png"; 
      if(chooseFile.ShowDialog() == DialogResult.OK) 
      { 
       Stream reader = File.OpenRead(chooseFile.FileName); 
       customerLogo = System.Drawing.Image.FromStream((Stream)reader); 

       MemoryStream finalStream = new MemoryStream(); 
       customerLogo.Save(finalStream, ImageFormat.Png); 

       // translate to image source 
       PngBitmapDecoder decoder = new PngBitmapDecoder(finalStream, BitmapCreateOptions.PreservePixelFormat, 
                BitmapCacheOption.Default); 
       NewCustomerLogo = decoder.Frames[0]; 
       newCustomer.Logo = newCustomer.Name + ".png"; 
      }    
     } 

     private ImageSource newCustomerLogo; 
     public ImageSource NewCustomerLogo 
     { 
      get 
      { 
       return newCustomerLogo; 
      } 
      set 
      { 
       newCustomerLogo = value; 
       OnPropertyChanged(new PropertyChangedEventArgs("NewCustomerLogo")); 
      } 
     } 
     #endregion 

     private Customer newCustomer = new Customer(); 
     public Customer NewCustomer 
     { 
      get { return newCustomer; } 
      set { newCustomer = value; OnPropertyChanged(new PropertyChangedEventArgs("NewCustomer")); } 
     } 

     #region PropertyChanged 
     public event PropertyChangedEventHandler PropertyChanged; 
     public void OnPropertyChanged(PropertyChangedEventArgs e) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, e); 
     } 
     #endregion 
    } 

CustomerListView

   <ListBox.ItemTemplate> 
       <!-- This DataTemplate is used for every Customer object in the ListBox.--> 
       <DataTemplate> 
        <Border BorderThickness="2" BorderBrush="Black" 
        Padding="10" Margin="10" 
        Name="CustomerBorder"> 

         <Grid Name="ItemGrid"> 
          <Grid.RowDefinitions> 
           <RowDefinition/> 
           <RowDefinition/> 
           <RowDefinition/> 
          </Grid.RowDefinitions> 
          <Grid.ColumnDefinitions> 
           <ColumnDefinition Width="100" /> 
           <ColumnDefinition Width="100" /> 
           <ColumnDefinition Width="*"/> 
          </Grid.ColumnDefinitions> 

          <!-- Logo picture --> 
          <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" HorizontalAlignment="Center" 
            Source="{helpers:ConcatString FrontString=../../Media/Images/Logos/, BindTo={Binding Path=Logo, FallbackValue=Default}}"       
            Height="{Binding ActualHeight, ElementName=ItemGrid}"/> 

          <!-- Customer name Row--> 
          <TextBlock Grid.Row="0" Grid.Column="1" Margin="10,0,8,0" FontWeight="Bold" 
           Name="CustomerTitle"> 
           Customer: 
          </TextBlock> 
          <TextBlock Grid.Row="0" Grid.Column="2" 
           Name="CustomerDataType" 
           Text="{Binding Path=Name}"> 
          </TextBlock> 

          <!-- Environment name Row--> 
          <TextBlock Grid.Row="1" Grid.Column="1" Margin="10,0,8,0" FontWeight="Bold" /> 
          <TextBlock Grid.Row="2" Grid.Column="1" Margin="10,0,8,0" FontWeight="Bold" /> 
         </Grid> 
        </Border>      
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

編輯:
這個截圖可能會讓我的疑惑更加清晰。 The problem 我通過CustomerAddView(Model)添加了testlogo.png,其他3個在VS解決方案資源管理器中正確添加。 正如你所見:

  • 標誌都在同一個目錄。
  • 只有通過VS解決方案資源管理器添加的徽標纔會顯示在VS解決方案資源管理器中。新的沒有。
  • 新徽標不會顯示在CustomerListView中。其他人做。

編輯2:
是它可能是更好的主意,將圖像保存到數據庫中,而不是保存的文件名作爲數據庫中的字符串?

+0

結合路徑當然應該是'NewCustomer.Logo'不'NewCustomerLogo'。除此之外,你不需要在任何單向綁定上設置'UpdateSourceTrigger = PropertyChanged'。這是多餘的,沒有效果。 – Clemens

+0

CustomerAddView窗口中的綁定工作正常,正如我已經說過的。這是CustomerListView(我剛剛在原始文章中添加),通過CustomerAddView添加時沒有顯示它,但是當我直接將它們添加到Visual Studio中時,它們確實有效。 – Kailayla

+0

你已經在輸出中看到了這個:'System.IO.IOException:Kan bron media/images/logos/testlogo.png niet vinden'?這顯然不是'../../ media/images/logos/testlogo.png'。 – Clemens

回答

0

MSDN說:

訪問存儲在應用程序包中的文件,但是從代碼 那裏沒有推斷root權限,指定MS-APPX: 方案。

var uri = new System.Uri("ms-appx:///images/logo.png"); 
+0

我試圖在XAML中使用這個應該得到標識的標籤,正如我在OP中發佈的那樣。我將圖像的Source屬性更改爲Source =「{helpers:ConcatString FrontString = ms-appx:/// Media/Images/Logos /,BindTo = {Binding Path = Logo,FallbackValue = Default}}」'不過,它會拋出一個異常,大部分與OP中的相同,但也是一個新的異常,它說:'NotSupportedException:'System.NotSupportedException:URI前綴不被識別# 當我剛剛放入Source =「ms-appx:/ //Media/Images/Logos/Vodafone.png「(我通過VS添加的圖像,這是工作b4)它沒有顯示,沒有img,也沒有例外。 – Kailayla

+1

該MSDN文章是關於Window Store/UWP應用程序,而問題是關於WPF。 ms-appx:// URI在WPF中不起作用。 – Clemens