'C#'에 해당되는 글 5건

  1. 2023.06.04 Wpf DataTemplate
  2. 2023.06.03 Wpf MVVM
  3. 2018.08.15 링크 정리하기
  4. 2016.12.29 DB접속해서 테이블 데이터 참조하기
  5. 2016.12.26 C# ArrayList
2023. 6. 4. 00:07

DataTemplate을 이용하면 데이터를 유연하게 표시할 수 있다.

참고 url: c# - Binding ContentControl Content for dynamic content - Stack Overflow

 

예제

<UserControl x:Class="ColorViews.DarkTurquoise"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008
             xmlns:local="clr-namespace:ColorViews"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Border Background="DarkTurquoise" />
    </Grid>
</UserControl>

 

using DemoLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ColorViews
{
    public class DarkTurquoiseViewModel : ViewModelBase
    {

    }
}

 

위와 같은 사용자정의 컨트롤을 만들었다.

이것을 메인 윈도우나 다른 컨트롤에 연결하려고 할경우 MVVM을 해치게 될 경우가 있다.

이럴때 간단하게 Xaml로 DataTemplate에 등록한 후 메인 뷰모델에서 인스턴스만 생성해 놓으면(물론 Prism같은 것을 사용하면 더 간단하고 Unity 같은 DI 프레임워크를 사용할 수 있지만, 없다고 가정한다.

 

<Window x:Class="PlainWpfApp.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:PlainWpfApp"
        xmlns:color="clr-namespace:ColorViews;assembly=ColorViews"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <DataTemplate DataType="{x:Type color:DarkTurquoiseViewModel}">
            <color:DarkTurquoise />
        </DataTemplate>
    </Window.Resources>
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <!--<StackPanel>
            <TextBlock Text="Test1" />
        </StackPanel>-->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.2*"/>
                <ColumnDefinition Width="0.8*"/>
            </Grid.ColumnDefinitions>
            <ContentControl Grid.Column="0" Content="{Binding DarkTurq}" />
        </Grid>
    </Grid>
</Window>

 

using ColorViews;
using DemoLibrary;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace PlainWpfApp
{
    public class MainWindowViewModel : ViewModelBase
    {
        private ViewModelBase _darkTurq;
        public ViewModelBase DarkTurq
        {
            get { return _darkTurq; }

            set
            {
                _darkTurq = value;
                this.NotifyPropertyChanged();
            }
        }


        public MainWindowViewModel()
        {
            DarkTurq = new DarkTurquoiseViewModel();   
        }



    }
}

'C#' 카테고리의 다른 글

Wpf MVVM  (0) 2023.06.03
링크 정리하기  (0) 2018.08.15
DB접속해서 테이블 데이터 참조하기  (0) 2016.12.29
C# ArrayList  (0) 2016.12.26
Posted by 다만사
2023. 6. 3. 22:11

1.

<Window x:Class="PlainWpfApp.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:PlainWpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <!--<StackPanel>
            <TextBlock Text="Test1" />
        </StackPanel>-->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.05*"/>
                <ColumnDefinition Width="0.9*"/>
                <ColumnDefinition Width="0.05*"/>
            </Grid.ColumnDefinitions>
            <Grid Grid.Column="1" Margin="0, 20, 0, 0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="30"/>
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.2*"/>
                        <ColumnDefinition Width="0.65*"/>
                        <ColumnDefinition Width="0.15*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" VerticalAlignment="Center" Text="単一値"/>
                    <TextBox Grid.Column="1" Margin="0, 0, 15, 0" VerticalAlignment="Center"
                             Text="{Binding SingleValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                    <Button Grid.Column="2" Content="Command" Command="{Binding ButtonCommand}" />
                </Grid>
                
            </Grid>
        </Grid>
    </Grid>
</Window>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace PlainWpfApp
{
    public class ActionCommand : ICommand
    {
        private readonly Action<object> action;
        private readonly Predicate<object> canExecute;

        public ActionCommand(Action<object> action) : this(action, null) { }

        public ActionCommand(Action<object> action, Predicate<object> canExecute)
        {
            this.action = action;
            this.canExecute = canExecute;
        }


        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            action(parameter);
        }
    }
}

 

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace PlainWpfApp
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {

        public ICommand ButtonCommand
        {
            get
            {
                return new ActionCommand(action => Save(), canExecute => CanSave());
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        public void Save()
        {
            MessageBox.Show("오승환 500 세이브!");
        }

        public bool CanSave()
        {
            return true;
        }

    }
}

 

 

2. CanExecute가 작동하도록 이벤트 코드 수정

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace PlainWpfApp
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {

        private string singleVal;

        public string SingleValue
        {
            get { return singleVal; }
            set
            {
                if (singleVal != value)
                {
                    singleVal = value;
                    this.NotifyPropertyChanged();
                }
            }
        }

        public ICommand ButtonCommand
        {
            get
            {
                return new ActionCommand(action => Save(), canExecute => CanSave());
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void Save()
        {
            MessageBox.Show("오승환 500 세이브! -- 메시지=" + this.SingleValue);
        }

        public bool CanSave()
        {
            return !string.IsNullOrEmpty(this.SingleValue);
        }

    }
}

 

ActionCommand도 수정

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace PlainWpfApp
{
    public class ActionCommand : ICommand
    {
        private readonly Action<object> action;
        private readonly Predicate<object> canExecute;

        public ActionCommand(Action<object> action) : this(action, null) { }

        public ActionCommand(Action<object> action, Predicate<object> canExecute)
        {
            this.action = action;
            this.canExecute = canExecute;
        }


        public event EventHandler? CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            action(parameter);
        }
    }
}

'C#' 카테고리의 다른 글

Wpf DataTemplate  (0) 2023.06.04
링크 정리하기  (0) 2018.08.15
DB접속해서 테이블 데이터 참조하기  (0) 2016.12.29
C# ArrayList  (0) 2016.12.26
Posted by 다만사
2018. 8. 15. 23:56

보통 1~100까지의 합 중에서 짝수의 합을 구하는 학원 예제가 있다

보통 자바나 C# 요즘엔 파이썬등으로 이런 프로그램을 짤때가 있다.

6개월 배우면 이런거 하나 정도는 건지고 가야 하는데,,,


그래서 보통 다음과 같이 코딩한다.


int[] Numbers = { 1, 2, 3, 4,5,6,7,8,9,10 };

            int? result = 0;

 

            foreach(intinNumbers)

            {

                if(i % 2 == 0)

                {

                    result = result + i;

                }

            }

 

            Console.WriteLine(result);



결코 나쁜 코딩이 아니다. 하지만 링크를 사용하면 다음과 같이 혁신적으로 코딩이 가능하다...


int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            intresult = Numbers.Where(x => x % 2 == 0).Sum();

            Console.WriteLine(result);

'C#' 카테고리의 다른 글

Wpf DataTemplate  (0) 2023.06.04
Wpf MVVM  (0) 2023.06.03
DB접속해서 테이블 데이터 참조하기  (0) 2016.12.29
C# ArrayList  (0) 2016.12.26
Posted by 다만사
2016. 12. 29. 00:17

DB는 엑세스로 해서


OleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Administrator\\Documents\\BookDB.accdb");


            cn.Open();

            OleDbCommand cmd = new OleDbCommand("select * from 책", cn);

            OleDbDataReader dr = cmd.ExecuteReader();


            while (dr.Read())

            {

                Console.WriteLine(dr["도서명"].ToString());

            }


            dr.Close();

            cn.Close();



혹시 오피스64비트로 깔아서 accdb파일 에러가 나면

https://social.msdn.microsoft.com/Forums/en-US/1d5c04c7-157f-4955-a14b-41d912d50a64/how-to-fix-error-the-microsoftaceoledb120-provider-is-not-registered-on-the-local-machine?forum=vstsdb&prof=required


여기서 두번째 링크 있는 것을 깔아주면 된다.

'C#' 카테고리의 다른 글

Wpf DataTemplate  (0) 2023.06.04
Wpf MVVM  (0) 2023.06.03
링크 정리하기  (0) 2018.08.15
C# ArrayList  (0) 2016.12.26
Posted by 다만사
2016. 12. 26. 22:46

쇼핑몰에서 물건을 담을때 쓰면 좋겠다.


 ArrayList shoppingCart = new ArrayList();

            shoppingCart.Add("컴퓨터");

            shoppingCart.Add("휴대폰");

            shoppingCart.Add("전자사전");


            Console.WriteLine("첫번째 요소:" + shoppingCart[0]);

            Console.WriteLine("요소의 갯수:" + shoppingCart.Count);

'C#' 카테고리의 다른 글

Wpf DataTemplate  (0) 2023.06.04
Wpf MVVM  (0) 2023.06.03
링크 정리하기  (0) 2018.08.15
DB접속해서 테이블 데이터 참조하기  (0) 2016.12.29
Posted by 다만사