Hey all, I am currently learning the ropes of WPF on my own and I did a
simple app of passing data from one page to another but then I stumbled
upon MVVM and after trying out the samples, I tried to implement a
simple app based on my own but I came across a problem...
Does anyone have any idea on how I could pass data from my view to my view model?
I took a look at the Mediator but I got no clue on how to implement it
and also I haven't got the slightest clue on most of the examples given
on the web...
I am trying to open a file dialog box and upon
textchanged, it would automatically display an image. This is simple to
do with direct events but it is so much complicated using MVVM... Below
are my failed attempt...
Hotel.Model
namespace Hotel.Model { public class MainModel { public MainModel() { }
public bool ConvertImageData(string uriSource, Image imageSource) { try { BitmapImage bitImage = new BitmapImage(); bitImage.BeginInit(); bitImage.UriSource = new Uri(uriSource); bitImage.EndInit(); imageSource.Source = bitImage; } catch (Exception e) { MessageBox.Show(e.Source.ToString()); //MessageBox.Show("Select an appropriate File Type."); } return true; }
public bool GetFileData(string path) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = @"Picture File (*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp | All Files (*.*)|*.*"; dlg.Title = "Insert a Hotel Image"; if (dlg.ShowDialog() == true) { path = dlg.FileName; } return true; }
} }
|
Hotel.EntryViewModel
namespace Hotel.ViewModel.ViewModels
{
public class EntryViewModel : BaseViewModel
{
private readonly MainModel model;
private RelayCommand imageCommand;
public EntryViewModel()
{
model = new MainModel();
}
public void GetImage()
{
/*
* Problem lies here...
* How do I get the selected file path based on the textbox in my view
* How do I get the name of the Image Control created in my view
*/
model.ConvertImageData(entryFilePath, entryImage);
}
public ICommand OpenImageCommand
{
get
{
if (imageCommand == null)
{
imageCommand = new RelayCommand(param => GetImage());
}
return imageCommand;
}
}
}
}
View
<Page x:Class="Hotel.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
<Grid>
<Button Name="browseBtn" Click="browseBtn_Click"
Margin="14,48.225,0,0" Height="23" VerticalAlignment="Top"
HorizontalAlignment="Left" Width="77" Command="{Binding
Path=OpenImageCommand}">Browse Image</Button>
<TextBox Height="22" Margin="0,50,50,0" x:Name="filePath"
VerticalAlignment="Top" IsUndoEnabled="True" IsReadOnly="False"
HorizontalAlignment="Right" Width="147" ></TextBox>
<Image Margin="103,78,50,117" x:Name="hotelImage" Stretch="Fill" />
</Grid>
</Page>
Any response or help would be helpful and much appreciated as I am
currently stuck here... It seems so much difficult to implement this
MVVM...
Thank you for your time.