반응형

 

wpf처럼 테마 적용법을 찾아내고 싶었으나 잘 안된다. 대신 material skin을 적용하면 쉽게 화면 스타일을 바꿀 수 있다.

 

1. NugetPackageManager GUI 설치

2. MaterialSkin 설치
 - VSCode에서 Ctrl+Shift+P ->Nuget Package Manager GUI에서 materialskin 검색

 

3. Form1.cs 파일에 적용

namespace winform_ex02;
using System;
using System.Text;
using System.Xml;
using MaterialSkin; 	//추가
using MaterialSkin.Controls;	//추가


// public partial class Form1 : Form
public partial class Form1 : MaterialForm
{
    public Form1()
    {
        InitializeComponent();
        // 아래 추가
        var materialSkinManager = MaterialSkinManager.Instance;
        materialSkinManager.AddFormToManage(this);
        materialSkinManager.Theme = MaterialSkinManager.Themes.DARK;
        materialSkinManager.ColorScheme=new ColorScheme(Primary.BlueGrey900, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
		// 여기까지		
        
        // 이하는 버튼 클릭 이벤트...
        this.button1.Click += new System.EventHandler(this.button1_Click);
    }

    private void button1_Click(object sender, EventArgs e)
	{
		OpenFileDialog openFileDlg = new OpenFileDialog();        
		openFileDlg.Filter = "XML Files (*.xml)|*.xml";
		openFileDlg.ShowDialog();
		// MessageBox.Show("Hello World!");
		if (openFileDlg.FileName.Length > 0)
		{
			foreach (string Filename in openFileDlg.FileNames)
			{
				this.textBox1.Text = Filename;                
				
				XmlDocument xmlDoc = new XmlDocument();  // XmlDocument 객체 생성
				xmlDoc.Load(Filename);                 // XML 파일 로드                               
				XmlNodeList allNodes = xmlDoc.SelectNodes("//bookstore//*");
				StringBuilder sb = new StringBuilder();
				
				foreach(XmlNode node in allNodes){
					if(node.NodeType == XmlNodeType.Element){
						sb.Append(node.InnerText);
					}
					else if (node.NodeType == XmlNodeType.Text){
						sb.Append(node.Value );
					}
					// sb.Append("\n");
					sb.Append(Environment.NewLine);
				}

				this.result1.Text = sb.ToString();
			}
		}
	}
}

 

ColorScheme클래스의 생성 인자

materialSkinManager.ColorScheme=new ColorScheme(Primary.BlueGrey900, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
        // 인자1 `Primary.BlueGrey900`: 테마의 기본 색상. 메인 강조 색상. 진한 청회색.
        // 인자2 `Primary.BlueGrey900`: 보조 색상으로 호버 색상. 초점 색상.
        // 인자3 `Primary.BlueGrey500`: 3차 색상. 배경색 or 은은한 그림자 색상으로 가끔 사용됨. 
        // 인자4 `Accent.LightBlue200`: 버튼, 링크 등 강조 색상. 연한 파란색
        // 인자5 `TextShade.WHITE`: 텍스트 음영

 

4. Form1.Designer.cs (버튼 클릭 이벤트/폼 예제)

namespace winform_ex02;

partial class Form1
{
    /// <summary>
    ///  Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    ///  Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    ///  Required method for Designer support - do not modify
    ///  the contents of this method with the code editor.
    /// </summary>
    private Button button1;
    private TextBox textBox1;
    private TextBox result1;
    private Panel panel1;
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Text = "Form1";

        // 버튼 컨트롤 생성 및 설정
        this.button1 = new System.Windows.Forms.Button();
        this.button1.Location = new System.Drawing.Point(10, 10);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(70, 50);
        this.button1.Text = "Click Me!";
        this.button1.UseVisualStyleBackColor = true;
        // this.button1.Click += new System.EventHandler(this.button1_Click);  // 클릭 이벤트 핸들러 등록

        // 버튼을 폼에 추가
        this.Controls.Add(this.button1);

        // 텍스트 박스 생성 및 추가
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.textBox1.Location = new System.Drawing.Point(10, 70);
        this.textBox1.Name = "textBox1";
        this.textBox1.Size = new System.Drawing.Size(500, 500);
        this.textBox1.Text = "";
        // this.textBox1.UseVisualStyleBackColor = true;
        this.Controls.Add(this.textBox1);

        // 패널 생성 및 추가  
        this.panel1 = new System.Windows.Forms.Panel();   
        this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom)));
        this.panel1.Location = new System.Drawing.Point(10, 100);   
        this.panel1.Name = "panel1";        
        this.panel1.Size = new System.Drawing.Size(1090,330);
        // this.panel1.TabIndex = 0;
        // this.panel1.Width = this.ClientSize.Width;
        // this.panel1.Height = this.ClientSize.Width;
        // this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.panel1.AutoScroll = true;
        this.panel1.BackColor = Color.DimGray;
        
        this.Controls.Add(this.panel1);

        // 텍스트 박스 생성 및 추가
        this.result1 = new System.Windows.Forms.TextBox();
        this.result1.Name = "resul1";
        this.result1.Multiline = true;    
        this.result1.Location = new System.Drawing.Point(0, 0);     
        this.result1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
        this.result1.Dock = System.Windows.Forms.DockStyle.Fill; // Dock 속성 설정
        this.result1.Text = "";

        // 텍스트 박스의 크기와 위치를 조정               
        // this.result1.Width = this.panel1.ClientRectangle.Width;
        // this.result1.Height = this.panel1.ClientRectangle.Height;        
        this.panel1.Controls.Add(this.result1);
    }

    #endregion
}

 

반응형
반응형

[ 목차 ]

    오랫만에 간단히 PC에서 XML파일의 텍스트를 읽어올 일이 있어서, 간단히 닷넷 winform으로 만들어봤습니다. winform은 정말 오랫만이라, 또 잊어버리기 전에 기록으로 남깁니다.

     

    해당 프로그램은 닷넷6.0, VSCode에서 만들어졌습니다.

     

    1. 닷넷 Winform 시작

    적당한 이름의 프로젝트 폴더를 만들고, 아래의 명령어어로 winform 프로젝트를 생성합니다.

    dotnet new winforms // 끝에 s가 들어감을 확인

     

    2. Form1.Designer.cs 으로 요소 추가하기

    우선 필요한 버튼, 파일경로를 나타내는 textbox, 그리고 추출 결과물을 표현할 textbox를 추가합니다.

    namespace wf01_xml;
    
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
    
        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    
        #region Windows Form Designer generated code
    
        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private Button button1;
        private TextBox textBox1;
        private TextBox result1;
        private Panel panel1;
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1100, 450);
            this.Text = "Form1";
    
            // 버튼 컨트롤 생성 및 설정
            this.button1 = new System.Windows.Forms.Button();
            this.button1.Location = new System.Drawing.Point(10, 10);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(70, 50);
            this.button1.Text = "Click Me!";
            this.button1.UseVisualStyleBackColor = true;
            // this.button1.Click += new System.EventHandler(this.button1_Click);  // 클릭 이벤트 핸들러 등록
    
            // 버튼을 폼에 추가
            this.Controls.Add(this.button1);
    
            // 텍스트 박스 생성 및 추가
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox1.Location = new System.Drawing.Point(10, 70);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(500, 500);
            this.textBox1.Text = "";
            // this.textBox1.UseVisualStyleBackColor = true;
            this.Controls.Add(this.textBox1);
    
            // 패널 생성 및 추가  
            this.panel1 = new System.Windows.Forms.Panel();   
            this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom)));
            this.panel1.Location = new System.Drawing.Point(10, 100);   
            this.panel1.Name = "panel1";        
            this.panel1.Size = new System.Drawing.Size(1090,330);
            // this.panel1.TabIndex = 0;
            // this.panel1.Width = this.ClientSize.Width;
            // this.panel1.Height = this.ClientSize.Width;
            // this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel1.AutoScroll = true;
            this.panel1.BackColor = Color.DimGray;
            
            this.Controls.Add(this.panel1);
    
            // 텍스트 박스 생성 및 추가
            this.result1 = new System.Windows.Forms.TextBox();
            this.result1.Name = "resul1";
            this.result1.Multiline = true;    
            this.result1.Location = new System.Drawing.Point(0, 0);     
            this.result1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.result1.Dock = System.Windows.Forms.DockStyle.Fill; // Dock 속성 설정
            this.result1.Text = "";
    
            // 텍스트 박스의 크기와 위치를 조정               
            // this.result1.Width = this.panel1.ClientRectangle.Width;
            // this.result1.Height = this.panel1.ClientRectangle.Height;        
            this.panel1.Controls.Add(this.result1);
    
    
    
    
    
        }
    
        #endregion
    }

     

    3. Form1.cs

    버튼을 누르면 파일탐색이 가능한 filedialog를 생성하고, 선택한 XML 파일로부터 데이터를 처리하도록 구성합니다. 특히 XML에서 각 노드의 값을 가져오는 부분은 불러오고자하는 파일의 형식에 맞게 수정하시기 바랍니다. 아직 미완성인 부분...

    namespace wf01_xml;
    using System;
    using System.Text;
    using System.Xml;
    
    public partial class Form1 : Form
    {
    	public Form1()
    	{        
    		InitializeComponent();
    		this.button1.Click += new System.EventHandler(this.button1_Click);
    	}
    
    	private void button1_Click(object sender, EventArgs e)
    	{
    		OpenFileDialog openFileDlg = new OpenFileDialog();        
    		openFileDlg.Filter = "XML Files (*.xml)|*.xml";
    		openFileDlg.ShowDialog();
    		// MessageBox.Show("Hello World!");
    		if (openFileDlg.FileName.Length > 0)
    		{
    			foreach (string Filename in openFileDlg.FileNames)
    			{
    				this.textBox1.Text = Filename;                
    				
    				XmlDocument xmlDoc = new XmlDocument();  // XmlDocument 객체 생성
    				xmlDoc.Load(Filename);                 // XML 파일 로드                               
    				XmlNodeList allNodes = xmlDoc.SelectNodes("//bookstore//*");
    				StringBuilder sb = new StringBuilder();
    				
    				foreach(XmlNode node in allNodes){
    					if(node.NodeType == XmlNodeType.Element){
    						sb.Append(node.InnerText);
    					}
    					else if (node.NodeType == XmlNodeType.Text){
    						sb.Append(node.Value );
    					}
    					// sb.Append("\n");
    					sb.Append(Environment.NewLine);
    				}
    
    				this.result1.Text = sb.ToString();
    			}
    		}
    	}
    }

     

    4. 샘플XML (Book.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
      <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J.K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
      </book>
      <book category="web">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
      </book>
    </bookstore>

     

    <결과>

    부모 노드에서는 자식노드들의 값을 모두 출력합니다. 원하는 결과는 아니지만 조금 더 수정하면 비슷하게 사용은 가능할 것 같습니다.

    반응형
    반응형

    아래와 같이 xaml에서 직접 작성할 수 있습니다.

    <?xml version="1.0" encoding="utf-8"?>
    <Window
    	x:Class="ebar.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    	Title="ebar"
    	Width="1175"
    	Height="704">
    	<Grid>
    		<DataGrid
    			FontFamily="Arial"
    			x:Name="worktable"
    			Height="133"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Stretch"
    			VerticalAlignment="Top"
    			Margin="30,128,34,0">
    			<DataGrid.Columns>
    				<DataGridTemplateColumn>
    					<DataGridTemplateColumn.Header>
    						<Grid Width="500">
    							<Grid.RowDefinitions>
    								<RowDefinition/>
    								<RowDefinition/>
    							</Grid.RowDefinitions>
    							<Grid.ColumnDefinitions>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    							</Grid.ColumnDefinitions>
    							<TextBlock Grid.ColumnSpan="2" HorizontalAlignment="Center" Text="Main Header1" Grid.Column="0" />
    							<TextBlock Grid.Row="1" Grid.Column="0" Text="Id1" />
    							<TextBlock Grid.Row="1" Grid.Column="1" Text="Name1" />
    							<TextBlock Grid.ColumnSpan="2" HorizontalAlignment="Center" Text="Main Header2" Grid.Column="2" />
    							<TextBlock Grid.Row="1" Grid.Column="2" Text="Id1" />
    							<TextBlock Grid.Row="1" Grid.Column="3" Text="Name2" />
    						</Grid>
    					</DataGridTemplateColumn.Header>					
    				</DataGridTemplateColumn>
    			</DataGrid.Columns>
    		</DataGrid>
    		<ComboBox
    			Height="20"
    			RenderTransformOrigin="0.5,0.6"
    			Width="120"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="158,75.5,0,0"></ComboBox>
    		<Label
    			x:Name="Project_Label"
    			Content="Project No"
    			Width="133"
    			Height="29"
    			Grid.Column="0"
    			Grid.Row="0"
    			VerticalAlignment="Top"
    			HorizontalAlignment="Left"
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Margin="35,70,0,0"
    			RenderTransformOrigin="0.5,0.5" />
    		<CheckBox
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="511,78.5,0,0" />
    		<Label
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Content="진행중 Only"
    			Width="84"
    			Height="26"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="427,74,0,0" />
    		<ComboBox
    			Width="120"
    			Height="20"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="683,75.5,0,0" />
    		<Label
    			Content="Unit(호기)"
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Width="123"
    			Height="23"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="560,74.5,0,0" />
    		<Label
    			Content="작업Category"
    			Width="100"
    			Height="28"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="886,71.5,0,0" />
    		<ComboBox
    			Width="120"
    			Height="20"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="994,76,0,0" />
    	</Grid>
    </Window>

    아래와 같이 C#코드로 작성할 수도 있습니다.

    /*
     * Created by SharpDevelop.
     * User: wijkim
     * Date: 2023-02-13
     * Time: 오후 2:56
     * 
     * To change this template use Tools | Options | Coding | Edit Standard Headers.
     */
    using System;
    using System.Collections.Generic;
    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;
    
    namespace ebar
    {
    	/// <summary>
    	/// Interaction logic for Window1.xaml
    	/// </summary>
    	public partial class Window1 : Window
    	{
    		public Window1()
    		{
    			InitializeComponent();
    			
    			DataGridTextColumn textColumn = new DataGridTextColumn();
    			textColumn.Header = "Column 1";
    			textColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    			textColumn.HeaderTemplate = new DataTemplate();
    			
    			FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));
    			stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Vertical);
    			
    			FrameworkElementFactory firstLine = new FrameworkElementFactory(typeof(TextBlock));
    			firstLine.SetValue(TextBlock.TextProperty, "First line");
    			firstLine.SetValue(TextBlock.FontSizeProperty, 16d);
    			firstLine.SetValue(TextBlock.FontWeightProperty, FontWeights.Bold);
    			
    			FrameworkElementFactory secondLine = new FrameworkElementFactory(typeof(TextBlock));
    			secondLine.SetValue(TextBlock.TextProperty, "Second line");
    			secondLine.SetValue(TextBlock.FontSizeProperty, 12d);
    			secondLine.SetValue(TextBlock.FontStyleProperty, FontStyles.Italic);
    			
    			stackPanel.AppendChild(firstLine);
    			stackPanel.AppendChild(secondLine);
    			
    			textColumn.HeaderTemplate.VisualTree = stackPanel;
    			
    			worktable.Columns.Add(textColumn);		
    		}
    	}
    }

     

    이 경우 XAML코드에서 필요없는 Column정의부분은 지워도 무관합니다.

    <?xml version="1.0" encoding="utf-8"?>
    <Window
    	x:Class="ebar.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    	Title="ebar"
    	Width="1175"
    	Height="704">
    	<Grid>
    		<DataGrid
    			FontFamily="Arial"
    			x:Name="worktable"
    			Height="133"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Stretch"
    			VerticalAlignment="Top"
    			Margin="30,128,34,0">
    			<!--<DataGrid.Columns>
    				<DataGridTemplateColumn>
    					<DataGridTemplateColumn.Header>
    						<Grid Width="500">
    							<Grid.RowDefinitions>
    								<RowDefinition/>
    								<RowDefinition/>
    							</Grid.RowDefinitions>
    							<Grid.ColumnDefinitions>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    								<ColumnDefinition/>
    							</Grid.ColumnDefinitions>
    							<TextBlock Grid.ColumnSpan="2" HorizontalAlignment="Center" Text="Main Header1" Grid.Column="0" />
    							<TextBlock Grid.Row="1" Grid.Column="0" Text="Id1" />
    							<TextBlock Grid.Row="1" Grid.Column="1" Text="Name1" />
    							<TextBlock Grid.ColumnSpan="2" HorizontalAlignment="Center" Text="Main Header2" Grid.Column="2" />
    							<TextBlock Grid.Row="1" Grid.Column="2" Text="Id1" />
    							<TextBlock Grid.Row="1" Grid.Column="3" Text="Name2" />
    						</Grid>
    					</DataGridTemplateColumn.Header>					
    				</DataGridTemplateColumn>
    			</DataGrid.Columns>-->
    		</DataGrid>
    		<ComboBox
    			Height="20"
    			RenderTransformOrigin="0.5,0.6"
    			Width="120"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="158,75.5,0,0"></ComboBox>
    		<Label
    			x:Name="Project_Label"
    			Content="Project No"
    			Width="133"
    			Height="29"
    			Grid.Column="0"
    			Grid.Row="0"
    			VerticalAlignment="Top"
    			HorizontalAlignment="Left"
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Margin="35,70,0,0"
    			RenderTransformOrigin="0.5,0.5" />
    		<CheckBox
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="511,78.5,0,0" />
    		<Label
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Content="진행중 Only"
    			Width="84"
    			Height="26"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="427,74,0,0" />
    		<ComboBox
    			Width="120"
    			Height="20"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="683,75.5,0,0" />
    		<Label
    			Content="Unit(호기)"
    			HorizontalContentAlignment="Center"
    			VerticalContentAlignment="Center"
    			Width="123"
    			Height="23"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="560,74.5,0,0" />
    		<Label
    			Content="작업Category"
    			Width="100"
    			Height="28"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="886,71.5,0,0" />
    		<ComboBox
    			Width="120"
    			Height="20"
    			Grid.Column="0"
    			Grid.Row="0"
    			HorizontalAlignment="Left"
    			VerticalAlignment="Top"
    			Margin="994,76,0,0" />
    	</Grid>
    </Window>

     

    반응형
    반응형

    dotnet core3.1 쓰다가 업그레이드 된 닷넷이 있다고 하여 dotnet6를 설치하고 스캐폴딩을 수행해보겠습니다.

     

    1. 필요한 라이브러리를 설치하고(Oracle DB)

    필요한 라이브러리도 설치됨

    2. 스캐폴딩......근데, 스캐폴딩하다가 에러가 발생했습니다.

    dotnet ef dbcontext scaffold "User Id=abc;Password=1234;Data Source=abcd.efghijk.com:1521/dbname;" Oracle.EntityFrameworkCore -t TBL_ITMAN_AUTH -t TBL_ITMAN_CONSUMABLE -t TBL_ITMAN_ERP -t TBL_ITMAN_OH_UPLOAD -t TBL_ITMAN_PRT_MDL -t TBL_ITMAN_PRT_MST -t TBL_ITMAN_P_C_RS -t TBL_ITMAN_REQ_CON -t TBL_ITMAN_USELOG -o Models -f
    지정된 명령 또는 파일을 찾을 수 없으므로 실행할 수 없습니다.
    가능한 원인은 다음과 같습니다.
      * 기본 제공 dotnet 명령 철자가 잘못 입력되었습니다.
      * .NET 프로그램을 실행하려고 했지만, dotnet-ef이(가) 없습니다.
      * 전역 도구를 실행하려고 했지만, 이 이름의 dotnet 접두사가 있는 실행 파일을 PATH에서 찾을 수 없습니다.

     

     

    찾다보니 아래와 같은 문구를 발견했는데요...

     

    이 도구는 더 이상 기본 제공되지 않으며 명시적인 설치가 필요하다는 ASP.NET Core 3 Preview 4 발표 를 참조하십시오 .

    dotnet ef 도구는 더 이상 .NET Core SDK의 일부가 아닙니다.

    이 변경 dotnet ef으로 전역 또는 로컬 도구로 설치할 수있는 일반 .NET CLI 도구로 제공 할 수 있습니다. 예를 들어, 마이그레이션 또는 스캐 폴드 a를 관리 하려면 다음 명령을 입력하여 전역 도구로 DbContext설치 dotnet ef하십시오.

     

    3. 결론은 아래와 같이 dotnet-ef를 전역으로 설치해줘야 한다고 합니다.

    dotnet tool install --global dotnet-ef

    그 후에는 잘 되네요..

    반응형
    반응형

    Dotnet 프로그램의 Icon을 변경하는 것은 굉장히 쉽습니다. 원하는 아이콘(111.ico)이미지를 프로젝트 폴더에 넣어준 뒤, project.csproj파일에 등록시켜주면 끝납니다.

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
    	<ApplicationIcon>111.ico</ApplicationIcon>
        <UseWPF>true</UseWPF>
    </PropertyGroup>

    반응형
    반응형

    https://www.c-sharpcorner.com/uploadfile/mahesh/printing-in-wpf/

     

    Printing in WPF

    This article discusses the process of printing in WPF and how to print a FlowDocument, Control, and Window in WPF.

    www.c-sharpcorner.com

    1. 단순 출력 기초

    <MainWindow.xaml>

    <Window x:Class="wpf10_767id.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:wpf10_767id"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Grid>
          <Button Content="printButton" Height="37" HorizontalAlignment="Left" Margin="22,21,0,0"  
                    Name="PrintSimpleTextButton" VerticalAlignment="Top" Width="134"  
                    Click="printButton_Click" /> 
        </Grid>
    </Window>

     

    <MainWindow.xaml.cs>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    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;
    
    namespace wpf10_767id
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                // this.PrintSimpleTextButton.Click += printButton_Click;
            }
            private void printButton_Click(object sender, RoutedEventArgs e)
            {
              // Create a PrintDialog  
              PrintDialog printDialog = new PrintDialog();  
              
              if(printDialog.ShowDialog().GetValueOrDefault())
              {
                FontFamily fontFamily =new FontFamily("나눔고딕코딩");
    
                FlowDocument doc = new FlowDocument(new Paragraph(new Run("출력 텍스트")));
                doc.Name="FlowDoc";    
    
                IDocumentPaginatorSource idpSource =  doc;    
    
                printDialog.PrintDocument(idpSource.DocumentPaginator, "(description)WPF Printing");            
                
              }
            }        
        }
    }

     

    2. 글씨체 편집

    <MainWindow.xaml.cs 수정>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    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;
    
    namespace wpf10_767id
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                // this.PrintSimpleTextButton.Click += printButton_Click;
            }
            private void printButton_Click(object sender, RoutedEventArgs e)
            {
              // Create a PrintDialog  
              PrintDialog printDialog = new PrintDialog();  
              
              if(printDialog.ShowDialog().GetValueOrDefault())
              {
                FontFamily fontFamily =new FontFamily("나눔고딕코딩");
    
                //// 함수 추가 ////
                // FlowDocument doc = new FlowDocument(new Paragraph(new Run("일부 텍스트가 있습니다.")));
                FlowDocument doc = CreateFlowDocument();  
                doc.Name="FlowDoc";    
    
                IDocumentPaginatorSource idpSource =  doc;    
    
                printDialog.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");
                
              }
            }  
    
            //// 함수 추가 ////
            private FlowDocument CreateFlowDocument()  
            {  
                // Create a FlowDocument  
                FlowDocument doc = new FlowDocument();  
                // Create a Section  
                Section sec = new Section();  
                // Create first Paragraph  
                Paragraph p1 = new Paragraph();  
                // Create and add a new Bold, Italic and Underline  
                Bold bld = new Bold();  
                bld.Inlines.Add(new Run("First Paragraph"));  
                Italic italicBld = new Italic();  
                italicBld.Inlines.Add(bld);  
                Underline underlineItalicBld = new Underline();  
                underlineItalicBld.Inlines.Add(italicBld);  
                // Add Bold, Italic, Underline to Paragraph  
                p1.Inlines.Add(underlineItalicBld);  
                // Add Paragraph to Section  
                sec.Blocks.Add(p1);  
                // Add Section to FlowDocument  
                doc.Blocks.Add(sec);  
                return doc;  
            }       
        }
    }

     

    3. 프린트 다이얼로그 안띄우고 출력하기

    <MainWindow.xaml.cs 수정>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Printing;
    using System.Text;
    using System.Threading.Tasks;
    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;
    
    namespace wpf_test06_print
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
            private void printButton_Click(object sender, RoutedEventArgs e)
            {
                // Create a PrintDialog  
                PrintDialog printDialog = new PrintDialog();  
    
                // 프린트 다이얼로그 안열고 출력하기
                var printers = new LocalPrintServer().GetPrintQueues();
                var selectedPrinter = printers.FirstOrDefault(p => p.Name == "Samsung SL-J1560 Series"); // 문자열을 실제 프린트 이름으로 변경
                if(selectedPrinter == null)
                {
                    MessageBox.Show("not found!");
                    return;
                }
                
                // 다이얼로그에서 값이 입력되면 폰트를 ...으로 설정
                // if(printDialog.ShowDialog().GetValueOrDefault())
                // {
                //     FontFamily fontFamily =new FontFamily("나눔고딕코딩");  
                // }
    
                FlowDocument doc = new FlowDocument(new Paragraph(new Run(ResultBox.Text)));
                doc.Name="FlowDoc";    
    
                IDocumentPaginatorSource idpSource =  doc;                    
                printDialog.PrintDocument(idpSource.DocumentPaginator, "(description)WPF Printing");
                
                // 그리드 출력이 필요할 땐 추가 작업이 필요함
                // PrintVisual 활용법 참조
                // Grid grid = new Grid(); 
                // grid.SetValue(FontFamilyProperty, fontFamily); 
                // grid.SetValue(FontSizeProperty , 32d );
                // Canvas canvas = new Canvas(); 
                // canvas.Width = printDialog.PrintableAreaWidth; 
                // canvas.Height = printDialog.PrintableAreaHeight; 
                // canvas.Background = null; 
                // canvas.Children.Add(grid); 
                // printDialog.PrintVisual(canvas, "Sample");
            }
    
            private void previewButton_Click(object sender, RoutedEventArgs e)
            {
                ResultBox.Text = textBox1.Text + textBox2.Text;
            }     
        }    
    }
    반응형
    반응형

    회사에서 Visual Studio를 안사주는데, GUI 프로그래밍은 해야겠고...

    Visual Studio Code를 이용해 Dotnet Core로 프로그래밍을 하다보니 Resource 추가하는 것도 쉽지 않네요. 잊기전에 적어놓습니다. 예를 들어 아래와 같이 ./Resources 라는 폴더를 프로젝트에 추가할 경우..

     

    .csproj 파일에 <Content> 태그 부분을 추가해줍니다.

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    	<PropertyGroup>
    		<OutputType>WinExe</OutputType>
    		<TargetFramework>netcoreapp3.1</TargetFramework>
    		<UseWPF>true</UseWPF>
    	</PropertyGroup>
    	<ItemGroup>
    		<PackageReference Include="MaterialDesignThemes" Version="4.2.1"/>
    		<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.11">
    			<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    			<PrivateAssets>all</PrivateAssets>
    		</PackageReference>
    		<PackageReference Include="Oracle.EntityFrameworkCore" Version="5.21.4"/>
    		<PackageReference Include="System.Data.SqlClient" Version="4.8.3"/>
    		<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.11"/>
    		<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.11"/>
    		<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.11"/>
            
    		<!-- 추가 -->
    		<Content Include="Resources\*.*">
    			<CopyToOutputDirectory>Always</CopyToOutputDirectory>
    		</Content>
    		<!-- 여기까지 -->
            
    	</ItemGroup>	
    </Project>

     

    이제 xaml파일에서 "\Resources\Image.jpg"와 같이 접근할 수 있습니다.

    (이거 잘 생각 안나면 절대경로로 하면 작동은 합니다.)

    반응형
    반응형

    오늘은 아래 유튜브 영상의 데스크탑 어플리케이션을 구현해보겠습니다.

    https://www.youtube.com/watch?v=qSP8v8Gi3XU

     

    1. 라이브러리 설치

    이번 영상에서는 Material Design과 LiveCharts를 사용합니다. 아래의 명령으로 Package를 설치해줍니다.

    dotnet add package MaterialDesignThemes --version 4.2.1 // material Design 설치
    dotnet add package LiveCharts.Wpf --version 0.9.7 // live chart 설치

    또는 Nuget GUI Manager 를 설치 후

     

    Shift + Ctrl + P 로 명령창에서 Nuget 입력 시 나타나는 명령을 수행합니다.

    그리고 Nuget Package Manager에서 아래와 같이 설치해줍니다. Material Design Themes와 Livecharts.wpf로 검색되는 패키지를 설치해줍니다.

    귀차니즘....끄적끄적..

     

    2. 라이브러리 적용

    Material Design을 적용해야합니다. 적용하는 방법은 구글에서 < material design xaml >이라고 검색하면 나오는데, 여기 사이트를 참조하시면 되겠습니다. 그리고, 나중에 livechart에서 사용할 스타일도 정의해놓겠습니다.

    <App.xaml>

    <Application x:Class="wpf_test04UT2.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:wpf_test04UT2"
                 xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
             <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
                </ResourceDictionary.MergedDictionaries>
                <Style TargetType="lvc:LineSeries">
                    <Setter Property="StrokeThickness" Value="3"></Setter>                
                    <Setter Property="Fill" Value="#4EFFFFFF"></Setter>                
                    <Setter Property="PointGeometrySize" Value="0"></Setter>
                    <Setter Property="LineSmoothness" Value="0"></Setter>
                </Style>
                <Style TargetType="lvc:Axis">
                    <Setter Property="ShowLabels" Value="False"></Setter>                
                    <Setter Property="IsEnabled" Value="False"></Setter>                                
                </Style>
            </ResourceDictionary>
        </Application.Resources>
    </Application>

     

    3. 메인프레임 구성

    메인 프레임에서는 전체적인 틀을 Grid 레이아웃으로 잡아주고, 좌측 그리드에 메뉴를 Material Design Icon으로 구성합니다.

    <MainWindow.xaml>

    <Window x:Class="wpf_test04UT2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:wpf_test04UT2"
            xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
            mc:Ignorable="d"
            Title="MainWindow" Height="850" Width="1200"
            WindowStartupLocation="CenterScreen"        
            WindowStyle="None"
            Background="{x:Null}"
            AllowsTransparency="True" Loaded="Window_Loaded">
        <Grid>
            <materialDesign:Card Margin="10" UniformCornerRadius="15">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="15*" />
                    </Grid.ColumnDefinitions>
                    <Grid.Resources>
                        <Style TargetType="materialDesign:PackIcon">
                            <Setter Property="Width" Value="30"></Setter>
                            <Setter Property="Height" Value="30"></Setter>
                        </Style>
                    </Grid.Resources>
                    <Grid Grid.Column="0">
                        <ListView Margin="0 15">
                            <ListViewItem HorizontalAlignment="Center" Margin="0 10">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="Resistor" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                            <ListViewItem HorizontalAlignment="Center" Margin="0 10">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="CircleSlice6" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                            <ListViewItem HorizontalAlignment="Center" Margin="0 10">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="CalendarBlankOutline" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                            <ListViewItem HorizontalAlignment="Center" Margin="0 10">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="EqualiserVertical" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                            <ListViewItem HorizontalAlignment="Center" Margin="0 10">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="ChatOutline" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                            <ListViewItem HorizontalAlignment="Center" Margin="0 60 0 0">
                                <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left" 
                                BorderBrush="{x:Null}" Foreground="Black" x:Name="btnExit" Click="btnExit_click">
                                    <StackPanel Margin="-5">
                                        <materialDesign:PackIcon Kind="ExitToApp" />
                                    </StackPanel>
                                </Button>
                            </ListViewItem>
                        </ListView>
                    </Grid>
                    <Grid Grid.Column="1" Background="#f6f5f8" Name="RenderPages">
                    
                    </Grid>
                </Grid>
            </materialDesign:Card>
        </Grid>
    </Window>

    이번 과제는 UI에 집중되어 있어서, cs파일에서는 별로 할일이 없습니다.

    <MainWindow.xaml.cs>

    using System.Windows;
    
    namespace wpf_test04UT2
    {
      /// <summary>
      /// Interaction logic for MainWindow.xaml
      /// </summary>
      public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                RenderPages.Children.Clear();
                RenderPages.Children.Add(new Dashboard());
            }
            private void btnExit_click(object sender, RoutedEventArgs e)
            {
                Application.Current.Shutdown();
            }
        }
    }

     

    4. 내부 Dashboard 작성

    메인프레임에 뿌려줄 '내부'를 별도파일(UserControl)로 구현합니다. Material Design 사용하니까 이쁘고 좋긴 한데, 코드가 길어지고....익숙해지는데 시간이 좀 필요하겠네요..

    <Dashboard.xaml>

    <UserControl x:Class="wpf_test04UT2.Dashboard"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:wpf_test04UT2"
            xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
            xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.wpf"
            mc:Ignorable="d"
            Height="850" Width="1100">
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="8*" />
            <ColumnDefinition Width="4*" />
          </Grid.ColumnDefinitions>
          <Grid.Resources>
            <Style TargetType="materialDesign:PackIcon">
              <Setter Property="Width" Value="30"></Setter>
              <Setter Property="Height" Value="30"></Setter>
            </Style>
          </Grid.Resources>
          <Grid Grid.Column="0" Background="#f6f6f8">
            <StackPanel Margin="10">
                <Grid Height="60">
                  <Button Style="{StaticResource MaterialDesignFloatingActionButton}" HorizontalAlignment="Left"
                  BorderBrush="{x:Null}" Background="{x:Null}">
                    <StackPanel Margin="5">
                      <materialDesign:PackIcon Kind="ReorderHorizontal" Foreground="Gray" />
                    </StackPanel>
                  </Button>
                  <ComboBox HorizontalAlignment="Right" Width="100" materialDesign:HintAssist.Hint="Last 15 Days">
                    <ComboBoxItem>
                      <TextBlock Text="Last 15 Days" />
                    </ComboBoxItem>
                    <ComboBoxItem>
                      <TextBlock Text="Last 30 Days" />
                    </ComboBoxItem>
                  </ComboBox>
                </Grid>
                <WrapPanel HorizontalAlignment="Center">
                  <Border BorderBrush="White" BorderThickness="5" Margin="20 0" CornerRadius="15">
                    <materialDesign:Card materialDesign:ShadowAssist.ShadowDepth="Depth0" UniformCornerRadius="15" BorderThickness="5"
                    BorderBrush="White" Width="110" Height="130" Background="#F6F6F8">
                      <StackPanel Margin="10">
                        <materialDesign:PackIcon Kind="Twitter" Foreground="#29A3EC" />
                        <TextBlock FontWeight="SemiBold" FontSize="25" Text="280K" Margin="0 10 0 0" />
                        <TextBlock FontSize="12" Text="Follwers" />
                        <materialDesign:PackIcon Kind="EllipsisHorizontal" HorizontalAlignment="Right" />
                      </StackPanel>
                    </materialDesign:Card>
                  </Border>
                  <Border BorderBrush="White" BorderThickness="5" Margin="20 0" CornerRadius="15">
                    <materialDesign:Card materialDesign:ShadowAssist.ShadowDepth="Depth0" UniformCornerRadius="15" BorderThickness="5"
                    BorderBrush="White" Width="110" Height="130" Background="#F6F6F8">
                      <StackPanel Margin="10">
                        <materialDesign:PackIcon Kind="Instagram">
                          <materialDesign:PackIcon.Foreground>
                            <LinearGradientBrush StartPoint="1,0" EndPoint="0.5,1">
                              <GradientStop Color="#912A73" Offset="0" />
                              <GradientStop Color="#FA8E22" Offset="1" />
                            </LinearGradientBrush>
                          </materialDesign:PackIcon.Foreground>
                        </materialDesign:PackIcon>
                        <TextBlock FontWeight="SemiBold" FontSize="25" Text="690K" Margin="0 10 0 0" />
                        <TextBlock FontSize="12" Text="Followers" />
                        <materialDesign:PackIcon Kind="EllipsisHorizontal" HorizontalAlignment="Right" />
                      </StackPanel>
                    </materialDesign:Card>
                  </Border>
                  <Border BorderBrush="White" BorderThickness="5" Margin="20 0" CornerRadius="15">
                    <materialDesign:Card materialDesign:ShadowAssist.ShadowDepth="Depth0" UniformCornerRadius="15" BorderThickness="5"
                    BorderBrush="White" Width="110" Height="130" Background="#F6F6F8">
                      <StackPanel Margin="10">
                        <materialDesign:PackIcon Kind="Youtube" Foreground="#29A3EC" />
                        <TextBlock FontWeight="SemiBold" FontSize="25" Text="2.3M" Margin="0 10 0 0" />
                        <TextBlock FontSize="12" Text="Follwers" />
                        <materialDesign:PackIcon Kind="EllipsisHorizontal" HorizontalAlignment="Right" />
                      </StackPanel>
                    </materialDesign:Card>
                  </Border>
                  <Border BorderBrush="White" BorderThickness="5" Margin="20 0" CornerRadius="15">
                    <materialDesign:Card materialDesign:ShadowAssist.ShadowDepth="Depth0" UniformCornerRadius="15" BorderThickness="5"
                    BorderBrush="White" Width="110" Height="130" Background="#F6F6F8">
                      <StackPanel Margin="10">
                        <materialDesign:PackIcon Kind="Facebook" Foreground="#29A3EC" />
                        <TextBlock FontWeight="SemiBold" FontSize="25" Text="60K" Margin="0 10 0 0" />
                        <TextBlock FontSize="12" Text="Follwers" />
                        <materialDesign:PackIcon Kind="EllipsisHorizontal" HorizontalAlignment="Right" />
                      </StackPanel>
                    </materialDesign:Card>
                  </Border>
                </WrapPanel>
                <materialDesign:Card Margin="30 20" UniformCornerRadius="20">
                  <StackPanel>
                    <Grid>
                      <TextBlock Margin="20" HorizontalAlignment="Left" FontWeight="SemiBold" Text="Instagram Subscribers" FontSize="18"/>
                      <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                        <TextBlock FontWeight="ExtraBold" FontSize="14" Text="&#xF06C;" FontFamily="wingdings" VerticalAlignment="Center" Foreground="#42A5F4" />
                        <TextBlock Text="Gained" HorizontalAlignment="Right" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="14" Margin="5 0 10 0"/>
                        <TextBlock FontWeight="ExtraBold" FontSize="14" Text="&#xF06C;" FontFamily="wingdings" VerticalAlignment="Center" Foreground="#F55F54" />
                        <TextBlock Text="Lost" HorizontalAlignment="Right" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="14" Margin="5 0 20 0" />
                      </StackPanel>
                    </Grid>
                    <lvc:CartesianChart Series="{Binding SeriesCollection}" Foreground="Black" Margin="10 0" Height="200">
                      <lvc:CartesianChart.AxisX>
                        <lvc:Axis Labels="{Binding Labels}" Separator="{x:Static lvc:DefaultAxes.CleanSeparator}" />
                      </lvc:CartesianChart.AxisX>
                      <lvc:CartesianChart.AxisY>  
                        <lvc:Axis LabelFormatter="{Binding Formatter}" />
                      </lvc:CartesianChart.AxisY>
                    </lvc:CartesianChart>
                  </StackPanel>              
                </materialDesign:Card>
                <WrapPanel HorizontalAlignment="Center">
                  <materialDesign:Card Margin="10" UniformCornerRadius="20" Padding="10">
                    <StackPanel>
                      <TextBlock Text="Key Matrics" Margin="10 20" FontWeight="SemiBold"/>
                      <Grid Height="150">
                        <Grid.ColumnDefinitions>
                          <ColumnDefinition />
                          <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                          <RowDefinition />
                          <RowDefinition />
                          <RowDefinition />
                          <RowDefinition />
                        </Grid.RowDefinitions>
                        <TextBlock Text="Clicks" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="13" FontWeight="SemiBold" />
                        <TextBlock Text="Links" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="13" FontWeight="SemiBold" />
                        <TextBlock Text="Followers" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="13" FontWeight="SemiBold" />
                        <TextBlock Text="Impressions" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="13" FontWeight="SemiBold" />
                        <StackPanel Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                          <TextBlock Text="10K" FontWeight="SemiBold" Margin="5 0" />
                          <ProgressBar Margin="5 0" Width="100" Height="8" Foreground="#FFFFFF13" Background="#FFE8E8E8" BorderBrush="#FFF3F349" Value="78" />
                          <TextBlock Text="12K" FontWeight="SemiBold" />
                        </StackPanel>
                        <StackPanel Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                          <TextBlock Text="10K" FontWeight="SemiBold" Margin="5 0" />
                          <ProgressBar Margin="5 0" Width="100" Height="8" Foreground="#FFFFFF13" Background="#FFE8E8E8" BorderBrush="#FFF3F349" Value="78" />
                          <TextBlock Text="12K" FontWeight="SemiBold" />
                        </StackPanel>
                        <StackPanel Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                          <TextBlock Text="10K" FontWeight="SemiBold" Margin="5 0" />
                          <ProgressBar Margin="5 0" Width="100" Height="8" Foreground="SeaGreen" Background="#FFE8E8E8" BorderBrush="SeaGreen" Value="78" />
                          <TextBlock Text="12K" FontWeight="SemiBold" />
                        </StackPanel>
                        <StackPanel Grid.Column="1" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                          <TextBlock Text="10K" FontWeight="SemiBold" Margin="5 0" />
                          <ProgressBar Margin="5 0" Width="100" Height="8" Foreground="SeaGreen" Background="#FFE8E8E8" BorderBrush="SeaGreen" Value="78" />
                          <TextBlock Text="12K" FontWeight="SemiBold" />
                        </StackPanel>                    
                      </Grid>
                    </StackPanel>
                  </materialDesign:Card>
                  <materialDesign:Card Margin="10" UniformCornerRadius="20" Background="#633648">
                    <StackPanel Margin="10">
                      <TextBlock Text="Engagged Users" FontSize="14" Foreground="White" TextAlignment="Center" />
                      <TextBlock Text="12.5K" TextAlignment="Center" Margin="0 5" Foreground="White" FontSize="18" />
                      <lvc:CartesianChart Margin="0 5" Series="{Binding LastHourSeries}" Hoverable="False" DataTooltip="{x:Null}" Height="160" Width="160">
                        <lvc:CartesianChart.AxisX>
                          <lvc:Axis MinValue="0" />
                        </lvc:CartesianChart.AxisX>
                      </lvc:CartesianChart>
                      <materialDesign:PackIcon Kind="ArrowUp" HorizontalAlignment="Center" Margin="0 5" Width="20" Height="20" Foreground="#62A78B" />
                    </StackPanel>
                  </materialDesign:Card>
                  <materialDesign:Card Margin="10" UniformCornerRadius="20" Background="#633648">
                    <StackPanel Margin="10">
                      <TextBlock Text="Page Impression" FontSize="14" Foreground="White" TextAlignment="Center" />
                      <TextBlock Text="12.5K" TextAlignment="Center" Margin="0 5" Foreground="White" FontSize="18" />
                      <lvc:CartesianChart Margin="0 5" Series="{Binding LastHourSeries1}" Hoverable="False" DataTooltip="{x:Null}" Height="160" Width="160">
                        <lvc:CartesianChart.AxisX>
                          <lvc:Axis MinValue="0" />
                        </lvc:CartesianChart.AxisX>
                      </lvc:CartesianChart>
                      <materialDesign:PackIcon Kind="ArrowUp" HorizontalAlignment="Center" Margin="0 5" Width="20" Height="20" Foreground="#62A78B" />
                    </StackPanel>
                  </materialDesign:Card>
                </WrapPanel>
            </StackPanel>
          </Grid>
          <StackPanel Grid.Column="1" Background="White">
            <WrapPanel VerticalAlignment="Top" Margin="20 20 20 10">
              <Button Style="{StaticResource MaterialDesignFloatingActionButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="Black">
                <StackPanel Margin="-5">
                  <materialDesign:PackIcon Kind="BellOutline" />
                </StackPanel>
              </Button>
              <Button Background="#FFFFEEFA" BorderBrush="#FFFFEEFA" Foreground="#FFF0689E" Margin="10 0" Height="40">
                <WrapPanel HorizontalAlignment="Center" >
                  <materialDesign:PackIcon Kind="GiftOutline" Width="25" Height="25" />
                  <TextBlock Text="2 NEW UPDATES" VerticalAlignment="Center" FontWeight="SemiBold" Margin="10 0" />
                </WrapPanel>
              </Button>
              <Button Style="{StaticResource MaterialDesignFloatingActionButton}" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="Black">
                <StackPanel Margin="-5">
                  <materialDesign:PackIcon Kind="BellOutline" />
                </StackPanel>
              </Button>
            </WrapPanel>
            <Border Margin="40 10" CornerRadius="20" Background="#FFFFFEFA">
              <Image Source="Images/aaa.jpg" Stretch="Uniform" x:Name="ImgCartoon" Height="150" />
            </Border>
            <Calendar Margin="45 10" />
            <materialDesign:Card Margin="20 10" Padding="5" UniformCornerRadius="20" HorizontalAlignment="Center">
              <WrapPanel Margin="10">
                <materialDesign:PackIcon Kind="HandPeace" Foreground="#FFC83D" VerticalAlignment="Center" Margin="10 0" />
                <TextBlock Margin="10 0" VerticalAlignment="Center">
                  <TextBlock.Inlines>
                    <Run Text="Say Hi To" />
                    <Run Text="Laith Hart" FontWeight="SemiBold" FontSize="14" />
                  </TextBlock.Inlines>
                </TextBlock>
                <Image Source="Images/bbb.jpg" Width="40" Height="40" x:Name="avatar1" Margin="10 0" />
              </WrapPanel>
            </materialDesign:Card>
            <materialDesign:Card Margin="20 10" Padding="5" UniformCornerRadius="20" HorizontalAlignment="Center">
              <WrapPanel Margin="10">
                <materialDesign:PackIcon Kind="HandPeace" Foreground="#FFC83D" VerticalAlignment="Center" Margin="10 0" />
                <TextBlock Margin="10 0" VerticalAlignment="Center">
                  <TextBlock.Inlines>
                    <Run Text="Say Hi To" />
                    <Run Text="Laith Hart" FontWeight="SemiBold" FontSize="14" />
                  </TextBlock.Inlines>
                </TextBlock>
                <Image Source="Images/bbb.jpg" Width="40" Height="40" x:Name="avatar2" Margin="10 0" />
              </WrapPanel>
            </materialDesign:Card>
          </StackPanel>
        </Grid>
    </UserControl>

     

    차트에 뿌려줄 데이터 및 동작을 cs파일에 구현합니다.

    <Dashboard.xaml.cs>

    using LiveCharts;
    using LiveCharts.Wpf;
    using System;
    using System.IO;
    using LiveCharts.Defaults;
    using System.Windows.Controls;
    using System.Windows.Media.Imaging;
    
    namespace wpf_test04UT2
    {
    
      public partial class Dashboard : UserControl
      {
        public SeriesCollection SeriesCollection { get; set; }
        public SeriesCollection LastHourSeries { get; set;  }
        public SeriesCollection LastHourSeries1 { get; set;  }
        public string[] Labels { get; set; }
        public Func<double,string> Formatter { get; set; }    
        public Dashboard()
        {
          InitializeComponent();
          SeriesCollection = new SeriesCollection{
            new StackedColumnSeries
            {
              Values = new ChartValues<double> {25, 52, 61, 89},
              StackMode = StackMode.Values,
              DataLabels = true
            },
            new StackedColumnSeries
            {
              Values = new ChartValues<double> {-15, -75, -16, -49},
              StackMode = StackMode.Values,
              DataLabels = true
            }
          };
          LastHourSeries = new SeriesCollection
          {
            new LineSeries
            {
              AreaLimit = -10,
              Values = new ChartValues<ObservableValue>
              {
                new ObservableValue(3),
                new ObservableValue(1),
                new ObservableValue(9),
                new ObservableValue(4),
                new ObservableValue(5),
                new ObservableValue(3),
                new ObservableValue(1),
                new ObservableValue(2),
                new ObservableValue(3),
                new ObservableValue(7),
              }
            }
          };
          LastHourSeries1 = new SeriesCollection
          {
            new LineSeries
            {
              AreaLimit = -10,
              Values = new ChartValues<ObservableValue>
              {
                new ObservableValue(13),
                new ObservableValue(11),
                new ObservableValue(9),
                new ObservableValue(14),
                new ObservableValue(5),
                new ObservableValue(3),
                new ObservableValue(1),
                new ObservableValue(2),
                new ObservableValue(3),
                new ObservableValue(7),
              }
            }
          };
          Labels = new[] { "Feb 7", "Feb8", "Feb 9", "Feb 10" };
          Formatter = GetValue => GetValue.ToString();
          DataContext = this;
          string imgCartoon = Directory.GetCurrentDirectory().ToString()+"\\Images\\aaa.jpg";      
          string imgavatar  = Directory.GetCurrentDirectory().ToString()+"\\Images\\bbb.jpg";   
          ImgCartoon.Source = new BitmapImage(new Uri(imgCartoon));
          avatar1.Source = new BitmapImage(new Uri(imgavatar));
          avatar2.Source = new BitmapImage(new Uri(imgavatar));
        }    
      }  
    }

     

    5. 결과

    좀 있어보이나요? 좌측 메뉴가 동영상 강좌랑 달리 스타일이 안들어간 것 같습니다만, 수정하기 귀찮네요..필요할 때 하다보면 되겠죠..??ㅠㅠ

     

    ~~~끝~~~

    반응형

    + Recent posts