D plug 41reputation points
Please I am looking for a reliable way to store images for/retrieve images from SQL Server database. I am using MVVM pattern in WPF. I've looked at everything I've seen on Google about this problem and all I see is that the image controls are linked directly to the code behind it. Note that I'm not using a code-behind pattern, I'm using a pure MVVM pattern, meaning my image check in the xaml shouldn't be ignoring the current process. What I need is a specific way to convert an image into an image control into a byte array and store it in the database and convert it back to image format and display it in the view when the SqlDatareader starts to work without binding. The image control goes directly to the underlying code. How would this happen, in my opinion or in my model? I'm just confused. Everything else is standard, from text boxes to date pickers. It's the images that give me a headache. Need help. If there is any material in the MVVM pattern for this process I'd love to see it. Thanks in advance.
Windows Demo Foundation
Windows Demo Foundation
Part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,357 questions
database server
database server
A family of relational database management and analytics systems from Microsoft for e-commerce, line-of-business, and data warehousing solutions.
9,717 questions
DOING#
DOING#
An object-oriented and type-safe programming language derived from the C language family, including support for component-oriented programming.
8,127 questions
XAML
XAML
An Extensible Markup Language (XML)-based language that allows developers to define a hierarchy of objects with a set of attributes and logic.
641 questions
Log in to follow
0{tel} lift
DaisyTian-1203 11.511reputation points
2020-12-21T09:10:21.257+00:00 @DPlug
You say you don't want to use any codeIt, and you just want to convert images to xaml? If you do, it will be impossible to implement now. I'm a bit confused that using MVVM doesn't conflict with converting images. If you don't mind, I'll try to give you a demo of converting MVVM images to cs.D plug 41reputation points
2020-12-21T16:17:18.55+00:00 I need an MVVM demo. can you send it to me. Show me what I can choose from them.
Peter Fleischer (former MVP) 18,381 peoplereputation points
2020-12-21T19:15:13.26+00:00 Hallo,
try minedemonstrationon Github.D plug 41reputation points
2020-12-21T19:26:45.277+00:00 (Video) WPF MVVM Step by Step ( Windows Presentation Foundation)So let me listen to Github and see what I can get out of it.
DaisyTian-1203 11.511reputation points
2020-12-23T01:53:31.557+00:00 @DPlug
Did Peter's presentation help you? Do you have a question?D plug 41reputation points
2020-12-23T15:20:21.683+00:00 The problem I am facing is how to save the image in the database. I don't just store the image, I store so much information along with the image. Image is just one of many fields I store in the database. Clicking the save button saves each field to the database.
Peter Fleischer (former MVP) 18,381 peoplereputation points
2020-12-23T17:08:58.847+00:00 Hallo,
If you are inserting a new record, you must use the INSERT Sql command and include all NOT NULL fields. To save only the image, you can use the UPDATE Sql command with the WHERE clause to find existing records, or use the INSERT Sql command if all other fields are NULL-able.You can use my demo, just select an image and change the insert to update. I can modify my demo if you tell us the techniques needed.
D plug 41reputation points
(Video) WPF Switching Views With Navigation Using MVVM And Dependency Injection2020-12-23T17:48:38.093+00:00 I am inserting and retrieving data into the database using stored procedures. In the demo, you bind the image control to the "ImageToShow" property of the View-Model class. What do you do if you want to save an image in a database?
Peter Fleischer (former MVP) 18,381 peoplereputation points
2020-12-23T18:35:34.897+00:00 Hallo,
See the InsertPictures method in my demo to save photos (images). This method loads an image from a file (recursively). Replace "foreach(String f in GetFilesRecursive(directory path))" if you are getting photos from elsewhere. To use a stored procedure, replace CommandText with the name of the procedure and set CommandType.D plug 41reputation points
2020-12-23T20:38:57.62+00:00 I thought I should send you a sample of my code so you can see what I'm struggling with.
D plug 41reputation points
2020-12-23T20:49:24.91+00:00 It is not just loading an image from a folder, but clicking a button called "Upload Image" opens the file explorer, the user selects the image and clicks OK, the image is loaded into the control image and on the page After the filling in the rest of the information, the user clicks the "Save" button and the image and all other information is saved in the database. But the image must be stored as a byte array. This is the functionality I've been struggling with for weeks. Need help. I also have a data layer.
D plug 41reputation points
2020-12-23T21:10:18.613+00:00 Let me make this clear. The real question is how can I extract the image from the image control without binding it directly to code, convert it to a byte array, and then store it in the database along with whatever other details the user fills in. Remember, we've already bound the image control to the code that fetches the image from the database. Now the problem is to extract the user selected image loaded in the image control and convert the image into a byte array and store it in the database along with other information like last name, first name, registration date etc . filled in by the user. This is the real challenge.
(Video) WPF in C# with MVVM using Caliburn MicroDaisyTian-1203 11.511reputation points
2020-12-24T03:10:12.177+00:00 @DPlugwhat is yours
You don't need to enter the image controls directly into the code
meaning is it? to which the image refersFigure 1ofFigure II;
Log in to comment
1 answer
Order by:more helpful
more helpful Topical senior
Peter Fleischer (former MVP) 18,381 peoplereputation points
2020-12-21T11:11:23.92+00:00 Hallo,
Try the demo below. The SQL Server connection string is stored in the settings. The demo shows creating an array, inserting an image into the array, and displaying the first image. If you have any questions, write me and I can expand this demo.XAML:
and code:
use System use System.Collections.Generic use System.Data use System.Data.SqlClient use System.IO use System.Linq use System.Text use System.Threading.Tasks use System.Windows use System.Windows.Controls, use System. Windows.Data, use System.Windows.Documents, use System.Windows.Input, use System.Windows.Media, use System.Windows.Media.Imaging, use System.Windows.Shapes, use System.Windows.Media. use io = System.IO, use dr = System.Drawing, use System.ComponentModel, use System.Runtime.CompilerServices, namespace WpfApp025 { public class ViewModel: INotifyPropertyChanged { public BitmapImage ImageToShow { get; put down? } public ICommand Cm > new WpfApp1.Helper.RelayCommand(CmdExec); } private int nr = 1; private void CmdExec(object obj) { switch (obj.ToString()) { case "Create": CreateaTable(); breaks? case "Fill" : InsertPictures(@"c:\temp"); breaks? capitalization "display": ShowImage(nr); breaks? default: pause; } } private void CreateaTable() { use(SqlConnection cn = new SqlConnection(WpfApp1. Properties. Settings.Default.cnSQL)) { cn.Open(); using (SqlCommand cmd = new SqlCommand { Connection = cn }) { // Drop previous table in SQL Server 2016 and later cmd.CommandText = "DROP TABLE IF EXISTS Table1?"; cmd.ExecuteNonQuery(); // Create table cmd.CommandText = "CREATE Table [Table1]([ID] int Identity, [FolderName] nvarchar(255), [FileName] nvarchar(255), [File Type] nvarchar(10), [Picture] image , constraint [PK_Table1] primary key ([ID]))"; cmd.ExecuteNonQuery(); } } } private void InsertPictures(string directorypath) { SqlParameter parFolderName, parFileName, parFileType; Using (SqlConnection cn = new SqlConnection(WpfApp1.Properties.Settings.Default.cnSQL)) { cn.Open(); Using (SqlCommand cmd = new SqlCommand { Connection = cn }) { cmd.CommandText = "INSERT. (FolderName, FileName, FileType, Picture) " + "VALUES (@FolderName,@FileName,@FileType,@Picture); " + "SELECT CAST(scope_identity() AS int); "; // Set parFolderName parameter once = cmd.Parameters.Add("@FolderName", SqlDbType.VarChar, 255); parFileName = cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 255); parFileType"scmd.Adle. , SqlDbType.VarChar, 10); parPicture = cmd.Parameters.Add("@Picture", SqlDbType.Image); foreach (string f in GetFilesRecursive(directorypath)) { use(dr.Image img = dr.Image.From f)) { int w = 800; int h = (int)(w * img.Height / img.Width); dr.Bitmap bmp = new dr.Bitmap(img, w, h); use (MemoryStream ms = new MemoryStream()) { bmp.Save(ms, dr.Imaging.ImageFormat.Jpeg); parFolderName.Value = io.Path.GetDirectoryName(f); parFileName.Value = io.Path.GetFileNameWithoutExtension); io .Path.GetExtension(f); parPicture.Value = ms.ToArray(); cmd.ExecuteNonQuery(); } } } } } } private IEnumerable
GetFilesRecursive(string directorypath) { foreach (stringbestand in Directory.GetFiles(directorypath, "*.jpg")) return retourbestand; foreach (var map in Directory.GetDirectories(directorypad)) GetFilesRecursive(map); } private void ShowImage(int ID) { gebruik (SqlConnection cn = nieuwe SqlConnection(WpfApp1.Properties.Settings.Default.cnSQL)) { cn.Open(); gebruik (SqlCommand cmd = nieuwe TREHEQL* = @ID", cn) ) { cmd.Parameters.AddWithValue("@ID", ID); SqlDataReader rdr = cmd.ExecuteReader(); if (rdr.Read()) { ImageToShow = LoadBitmapImage((byte[])rdr["图片"]) ;OnPropertyChanged(nameof(ImageToShow));} } } } private statische BitmapImage LoadBitmapImage(byte[] imageData) {if (imageData == null || imageData.Length == 0) return null;var image = new BitmapImage(); gebruik (var mem = nieuwe MemoryStream(imageData)) { mem.Position = 0; image.BeginInit(); image.CreateOptions = BitmapCreateOptions.PreservePixelFormat; image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = null; image.StreamSource = memory; image.EndInit(); } image.Freeze(); 内容合后; } #region PropertyChanged 公共事件 PropertyChangedEventHandler PropertyChanged; internal void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, nieuwe PropertyChangedEventArgs(propName)); #eindregio }} 0 commentsWithout comment
Log in to comment
Log in to reply
Activity
Log in to track issues and users
FAQs
Should you use MVVM with WPF? ›
The Windows Presentation Framework (WPF) takes full advantage of the Model-View-ViewModel (MVVM) pattern. Though it is possible to create WPF applications without using the MVVM pattern, a little investment in learning can make building WPF applications much simpler.
What is MVVM in C# WPF? ›MVVM (Model-View-ViewModel)
MVVM is a way of creating client applications that leverages core features of the WPF platform, allows for simple unit testing of application functionality, and helps developers and designers work together with less technical difficulties.
MVVM – First Application
Step 1 − Create a new WPF Application project MVVMDemo. Step 2 − Add the three folders (Model, ViewModel, and Views) into your project. Step 4 − Add another StudentViewModel class into ViewModel folder and paste the following code.
- Introduction to MVVM C# ...
- The three components act as a team by referencing each other in the following pattern as follows: ...
- Next create three folders for Model, View, and ViewModel and remove the existing ManiWindow. ...
- Next, build new items and each of the correspondings to the separate components.
MVVM separates your view (i.e. Activity s and Fragment s) from your business logic. MVVM is enough for small projects, but when your codebase becomes huge, your ViewModel s start bloating. Separating responsibilities becomes hard. MVVM with Clean Architecture is pretty good in such cases.
What is the main advantages of MVVM? ›Advantages of using MVVM Design Pattern
Your code is decoupled. The package structure is even easier to navigate. The project is even easier to maintain. Your team can add new features even more quickly.
MVVM stands for Model, View, ViewModel. It is an architectural pattern implemented in applications to separate user interface code from data and business logic. With a clear separation of these components, all components of the app can be unit-tested, components can be reused within the app or across the app.
What is the difference between MVVM and MVC in C# WPF? ›Key Differences between MVC and MVVM
In MVC, the controller is the entry point to the Application, while in MVVM, the view is the entry point to the Application. MVC Model component can be tested separately from the user, while MVVM is easy for separate unit testing, and code is event-driven.
MVVM Design Pattern is the structural design pattern that separates the objects into three major components; they are Model, View, and ViewModel. This software design pattern separates into program logic, and user interface controls.
Is MVVM better than MVC? ›MVVM is better than MVC/MVP because of its unidirectional data and dependency flow. Dependency is one way, thus it is a lot easier to decouple it when we need to. It is also easier for testing.
How to use WPF in C#? ›
- Open Visual Studio.
- Select Create a new project.
- In the Search for templates box, type wpf, and then press Enter .
- In the code language dropdown, choose C# or Visual Basic.
- In the templates list, select WPF Application and then select Next. ...
- In the Configure your new project window, do the following:
To package content for navigation, WPF provides the Page class. You can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. WPF uses the journal to remember pages that have been navigated from and to navigate back to them.
What are the components of MVVM? ›- Activity/Fragment: These are the classes in which we place the different views with which the user interacts. ...
- ViewModel: A ViewModel class is a class where we perform functions either which are related to the business logic or independent of the UI.
The major difference between "Model" and "ViewModel" is that we use a ViewModel only in rendering views. We put all our ViewModel classes in a "ViewModels" named folder, we create this folder. Let's assume we want to implement a view page that will have three textboxes for Username, Password and Re-enter Password.
What are the elements of MVVM? ›There are three core components in the MVVM pattern: the model, the view, and the view model. Each serves a distinct purpose.
What is the disadvantage of MVVM? ›- Communication between various MVVM components and data binding can be painful.
- Code reusability of views and view model is difficult.
- Managing view models and their state in nested views and complex UI's is difficult.
- MVVM for beginners is hard to put to use.
Short Answer: Don't use MVVM if you are not using WPF/Silverlight/any technology I know with powerful automatic binding. Long Answer: No other pattern facilitates unit testing better than MVVM in WPF/Silverlight.
Is MVVM a clean architecture? ›MVVM with Clean Architecture is pretty good in such cases. It goes one step further in separating the responsibilities of your code base. It clearly abstracts the logic of the actions that can be performed in your app. Note: You can combine Clean Architecture with the model-view-presenter (MVP) architecture as well.
What are the roles and responsibilities of MVVM? ›ViewModel Responsibilities
ViewModel is the main point of MVVM application. The primary responsibility of the ViewModel is to provide data to the view, so that view can put that data on the screen. It also allows the user to interact with data and change the data.
The repository pattern is a design pattern that isolates the data layer from the rest of the app. The data layer refers to the part of your app, separate from the UI, that handles the app's data and business logic, exposing consistent APIs for the rest of your app to access this data.
How can you explain view and view model in MVVM? ›
Model–view–viewmodel (MVVM) is an architectural pattern in computer software that facilitates the separation of the development of the graphical user interface (GUI; the view)—be it via a markup language or GUI code—from the development of the business logic or back-end logic (the model) such that the view is not ...
What is MVVM and how does it work what is the use of live data? ›ViewModel object acts as an intermediate between View and the Model, meaning it provides data for the UI components like fragments or activities. It also includes an observable data holder called LiveData that allows ViewModel to inform or update the View whenever the data get updated.
What is the difference between Windows Forms and WPF in C#? ›WPF uses a more modern approach to layout that is based on XAML, while WinForms uses a more traditional approach that is based on forms and controls. This means that WPF provides more flexibility and control over the layout and appearance of the UI, while WinForms is simpler to use for basic UI design.
What is the difference between C# and WPF? ›Answers. WPF is a framework, you don't program with it, you program on it. You use a language, like C# to write a program based on a framework, like WPF. If you're just starting out, I'd stick with a C# Console Application until you're comfortable with the syntax and structure of C#.
How to choose between MVC and MVVM? ›MVVM separates the different components of the development process into three categories, model, view and ViewModel. This typically involves code markup or graphical user interfaces (GUI). MVC, or model-view-control is a way developers separate programs into these three components.
How does MVVM architecture work? ›What is MVVM in Android? MVVM means a way to structure code. With MVVM, it is possible to keep the UI components of an application away from the business logic. Furthermore, the business logic itself is kept away from the database operations.
Does MVVM have a controller? ›Both MVC and MVVM architectures contain a Controller piece. In fact, every software project has a Controller piece, since every software project manipulates data.
Is MVVM 3 tier architecture? ›MVVM is arguably a three layer architecture itself. Those layers all exist within the same application.
Why is MVC obsolete? ›Because the Controller's only job is to serve as a divider or border between the two other layer, it has lost its purpose, so we can happily let controllers go whereever they want. Backend developers need new patterns — or better put, need to learn old patterns to replace MVC.
Is MVVM deprecated? ›The MVVM Toolkit is inspired by MvvmLight, and is also the official replacement for it now that the library has been deprecated.
Which language is used in WPF? ›
WPF employs XAML, an XML-based language, to define and link various interface elements. WPF applications can be deployed as standalone desktop programs or hosted as an embedded object in a website.
What is the purpose of WPF? ›WPF provides a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2D and 3D graphics, animation, styles, templates, documents, media, text, and typography.
What are the types of WPF application in C#? ›WPF applications can be of two types: desktop-based applications and web-based applications. The desktop applications are normal . EXE executables, whereas the web-based browser applications are the .
How do I pass a value from one window to another in WPF? ›Just make a overload constructor which takes parameters of the window in which you want to retrieve. Suppose we want a user to login from our Main Window( i.e Login Window ) and we want to pass an int ID / string Email to our second form to retrieve data of logging user.
How do I call one window from another window in WPF? ›In WPF we have a couple of options by using the Show() and ShowDialog() methods. Well, if you want to close the opened window when a new window gets open then you can use the Show() method: Window1 win1 = new Window1(); win1. Show(); win1.
How do I create a user control in WPF? ›...
After that, create the control using the following syntax:
- <Grid x:Name="LayoutRoot">
- <local:XamlFileBrowser />
- </Grid>
MVVM isn't outdated, but it was overplayed to begin with.
Is WPF being deprecated? ›According to the documentation Overview - Product end of support, there are no plans to remove wpf. So it will be supported.
What is the difference between model and ViewModel in MVVM? ›The major difference between "Model" and "ViewModel" is that we use a ViewModel only in rendering views. We put all our ViewModel classes in a "ViewModels" named folder, we create this folder. Let's assume we want to implement a view page that will have three textboxes for Username, Password and Re-enter Password.
What is the difference between MVVM and MVC patterns? ›MVVM separates the different components of the development process into three categories, model, view and ViewModel. This typically involves code markup or graphical user interfaces (GUI). MVC, or model-view-control is a way developers separate programs into these three components.
What is the best MVVM framework? ›
- MVVM Toolkit.
- MVVM Foundation.
- WPF Application Framework (WAF)
- Light MVVM.
- Caliburn.
- Cinch.
- Prism.
- ReactiveUI.
MVP: This software architecture has a dependent user interface as it uses the presenter to act as a link between the view and the model. MVVM: MVVM implements data binding and allows easy separation of the model and the view.
Is WPF still used 2023? ›WPF is definitely not dead. The WPF project was open sourced by Microsoft and published on GitHub [2]. There is even a public roadmap for WPF with target dates for 2022.
What will replace WPF? ›- Platform Uno.
- Avalonia.
- Blazor.
- Ooui.
The pattern is often used in Windows and web graphics presentation software. The MVVM pattern is used in Windows Presentation Foundation (WPF), which runs on Microsoft's .
Why choose MVC over MVVM? ›MVC Model component can be tested separately from the user, while MVVM is easy for separate unit testing, and code is event-driven. MVC architecture has “one to many” relationships between Controller & View, while in MVVC architecture, “one to many” relationships between View & View Model.
What is the disadvantage of using design pattern? ›Disadvantages. Using design patterns requires extensive knowledge. Having design patterns available can also lead to people believing that apparently all problems can be solved using existing design patterns. In short, this can limit creativity and the desire to find new (better) solutions.