2013-06-26 4 views
0

Добрый день, Я пытаюсь сделать приложение, чтобы выполнить некоторые основные изменения на фотографиях. Я привязал коллекцию к списку, и я могу получить всю мою текстовую информацию, чтобы заполнить, но я не могу показать свое изображение. Каждый пример, который я вижу, устанавливает изображение с помощью uri, однако я не делал этого, чтобы создать свое изображение, и я не уверен, что именно поэтому. Я знаю, что изображение выглядит правильно загруженным, так как отображаются все свойства изображения (высоты пикселей по высоте). Я считаю, что я удалил весь код, не связанный с проблемой.Проблема с C# wpf binding image

Заранее спасибо, Chris

XML

<!--Step 1--> 
     <GroupBox x:Name="Step1"> 
      <Grid> 
       <StackPanel> 
        <Label>Select Pictures</Label> 
        <ListBox x:Name="PictureNames" ItemsSource="{Binding}" Height="auto"> 
         <ListBox.ItemTemplate> 
          <DataTemplate> 
           <StackPanel Orientation="Horizontal"> 
            <Image x:Name="CurrentPhoto" Width="300" Height="200" Source="{Binding CurrentPhoto}"/> 
            <!--old code trying to make this work <Canvas x:Name="CurrentPhoto" Width="300" Height="200" Background="{Binding CurrentPhoto}"/>--> 
            <TextBlock x:Name="Name" Text="{Binding Path=Name}"></TextBlock> 
           </StackPanel> 
          </DataTemplate> 
         </ListBox.ItemTemplate> 

        </ListBox> 
        <Button x:Name="AddPicture" Click="AddPicture_Click">Click to upload Pictures</Button> 
       </StackPanel> 
      </Grid> 
     </GroupBox> 

КОД

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using Microsoft.Win32; 
using System.Collections.ObjectModel; 

namespace S2IPictureWatermarker 
{ 
/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 

    ObservableCollection<picture> Pictures; 
    Position ThisStep = new Position(); 
    public MainWindow() 
    { 
     InitializeComponent(); 
     Startup(); 

    } 

    private void Startup() 
    { 
     ThisStep.CurrentStep = 1; 
     Pictures = new ObservableCollection<picture>(); 
     Step1.Visibility = System.Windows.Visibility.Visible; 
     Step2.Visibility = System.Windows.Visibility.Collapsed; 
     Step3.Visibility = System.Windows.Visibility.Collapsed; 
     Step4.Visibility = System.Windows.Visibility.Collapsed; 
    } 

    //GroupEditLstBx.ItemsSource = SelectedPhotos 

    private void AddPicture_Click(object sender, RoutedEventArgs e) 
    {//add picture to list of pictures 
     //get photo(s) location 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
     InitializeOpenFileDialog(openFileDialog1); 
     Nullable<bool> result = openFileDialog1.ShowDialog(); 
     //if photos are found, add to collection 
     if (result == true) 
      CreatePictureCollection(openFileDialog1.FileNames); 
    } 

    private void CreatePictureCollection(string[] FullPathNames) 
    { 
     foreach (string pathName in FullPathNames) 
     { 
      picture newPicture = new picture(); 
      newPicture.NewPicture(pathName); 
      if(Pictures.Count >= 1) 
      {//dont do anything 
      } 
      else 
      { 
       PictureNames.ItemsSource = Pictures; 
      } 
      Pictures.Add(newPicture); 

     } 
    } 

    private void InitializeOpenFileDialog(OpenFileDialog openFileDialog1) 
    { 
     // Set the file dialog to filter for graphics files. 
     openFileDialog1.Filter = 
      "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + 
      "All files (*.*)|*.*"; 

     // Allow the user to select multiple images. 
     openFileDialog1.Multiselect = true; 
     //     ^^^^^^^

     openFileDialog1.Title = "My Image Browser"; 

    } 
} 
} 

КОД ДЛЯ класса изображения

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.IO; 
using System.ComponentModel; 

namespace S2IPictureWatermarker 
{ 
    class picture : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     private int height; 

     public int Height 
     { 
      get { return height; } 
      set { height = value; OnPropertyChanged("Height"); } 
     } 
     private int width; 

     public int Width 
     { 
      get { return width; } 
      set { width = value; OnPropertyChanged("Width"); } 
     } 

     private string type; 

     public string Type 
     { 
      get { return type; } 
      set { type = value; OnPropertyChanged("Type"); } 
     } 

     private string location; 

     public string Location 
     { 
      get { return location; } 
      set { location = value; OnPropertyChanged("Location"); } 
     } 

     private string name; 

     public string Name 
     { 
      get { return name; } 
      set { name = value; OnPropertyChanged("Name"); } 
     } 

     private int orgHeight; 

     public int OrgHeight 
     { 
      get { return orgHeight; } 
      set { orgHeight = value; OnPropertyChanged("OrgHeight"); } 
     } 

     private int orgWidth; 

     public int OrgWidth 
     { 
      get { return orgWidth; } 
      set { orgWidth = value; OnPropertyChanged("OrgWidth"); } 
     } 

     private Image currentPhoto; 

     public Image CurrentPhoto 
     { 
      get { return currentPhoto; } 
      set { currentPhoto = value; OnPropertyChanged("CurrentPhoto"); } 
     } 

     //methods 
     //NEW PICTURE 
     public bool NewPicture(string PictureFullPath) 
     { 
      bool Created = false; 
      try 
      { 
       //set path(location), name, type 
       Location = Path.GetPathRoot(PictureFullPath);     
       Name= Path.GetFileNameWithoutExtension(PictureFullPath); 
       Type = Path.GetExtension(PictureFullPath); 


       //set current image 
       CurrentPhoto = Image.FromFile(PictureFullPath); 
       //set height and width 
       Height = CurrentPhoto.Height; 
       Width = CurrentPhoto.Width; 

       Created = true; 
      } 
      catch (Exception) 
      { 

       throw; 
      } 
      return Created; 
     } 


     //create the OnPropertyChanged method to raise 
     protected void OnPropertyChanged(string changedName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(changedName)); 
      } 
     } 
    } 
} 

ответ

0

Я считаю, что вы не можете поместить System.Windows.Image на фоне элемента canvas. Это потому, что System.Windows.Image является UIElement и не может использоваться как кисть. Вы можете создать ImageBrush из ImageSource (по Uri) и поместить его в фоновый режим. Или вы можете создать ContentControl вместо своего элемента canvas и поместить в него изображение из презентатора.

+0

моя ошибка, эта строка должна читать <Изображение x: Name = "CurrentPhoto" Width = "300" Height = "200" Source = "{Binding CurrentPhoto}" /> Я играл с разными объектами, чтобы увидеть, если я может заставить его работать. Теперь я собираюсь попробовать маршрут contentcontrol, чтобы убедиться, что это сработает. – chris

+0

, поэтому вам понадобится объект [System.Windows.Media.ImageSource] (http://msdn.microsoft.com/ru-ru/library/system.windows.media.imagesource.aspx) в свойстве ведущего. или используйте ContentControl вместо Canvas. – sedovav

+0

вы можете [конвертировать файлы в Uri] (http://stackoverflow.com/questions/1546419/convert-file-path-to-a-file-uri), если это корень проблемы – sedovav

0

Привет, попробуйте что-то подобное в элементе холста.

<Canvas.Background> 
        <ImageBrush ImageSource="{Binding CurrentPhoto}" Stretch="UniformToFill"></ImageBrush> 
</Canvas.Background> 

EDIT: Если это не работает сделать вашу собственность "CurrentPhoto" на ImageBrush.

+0

Я пробовал его в своем коде и не мог видеть ничего до изображения. вы могли заставить его работать? – chris

+0

Вы пытались сделать изображение ImageBrush вместо использования изображения? – Tan

+0

Действительно ли нужно использовать холст?если не пытаться использовать элемент изображения. Но если вы действительно хотите использовать холст, вам нужно преобразовать свойство CurrentPhoto в изображение. – Tan