[ 사용 예시 ]

상품리스트에서 관리자 번호로 저장해놓았을 경우 해당 관리자 번호의 이름을 가져와 사용자에게 보여주고 싶을 때 구현한다.

 

 

[ 구현 방법 ]

1.   Helper 폴더 아래 -> ManagerNameConverter 클래스 생성

 

2.     IValueConverter 상속 및 인터페이스 구현하기

 

- IValueConverter 를 상속 후 빨간 밑줄이 쳐졌을 경우 마우스를 갖다대고 , using System.Windows.Data; 누르기

- 다시 한번 빨간 밑줄 쳐졌을 경우 마우스를 갖다대고 , 인터페이스 구현 누르기

- 아래와 같이 기본 인터페이스 구현됬는지 확인하기

3. 상품에 저장한 관리자 번호를 받아온다.

4.     받아 온 관리자 번호를 관리자 이름으로 변환시킨다

5.   상품 리스트 보여주는 UserControl (혹은 window/page...)의 xaml 에서 바인딩 시켜준다.

-  UserControl에 Resource 추가하기

- 관리자 출력하는 datagrid에 바인딩시키기

<DataGridTextColumn Header="관리자" Width="1.5*" Binding="{Binding ManagerNum, Converter={StaticResource ManagerNameConver}}" />

반응형

[ INotifyPropertyChanged 는 언제 쓰는 것일까? ]

 

원본 속성 또는 대상 속성이 변경되면 다른 항목이 자동으로 업데이트되도록 하고 싶을 때, INotifyPropertyChanged 를 구현한다.

 

사용예시) 관리자가 추가,수정,삭제 될때마다 변동된 데이터를 바로 전체 프로그램에 반영시키고 싶을 경우

 

 

[ INotifyPropertyChanged 구현방법 ]

 

1.   INotifyPropertyChanged를 상속받는다.

2.   인터페이스를 구현한다.

 

- 빨간 물결밑줄이 쳐진 INotifyPropertyChanged 위에 마우스 커서를 올려놓으면 뜨는 창에서 잠재적 수정 사항 표시를 클릭한다 

- using System.ComponentModel; 을 클릭한다

- 다시 한번더 , 빨간 물결밑줄이 쳐진 INotifyPropertyChanged 위에 마우스 커서를 올려놓으면 뜨는 창에서 잠재적 수정 사항 표시를 클릭한다 

- 인터페이스 구현을 클릭한다

- 해당 코드가 생성된 것을 확인한다.

 

3.   OnPropertyChanged 메서드를 생성한다.

-  public event PropertyChangedEventHandler PropertyChanged; 코드 아래에 밑의 코드를 추가시킨다

 

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

 

-     OnPropertyChanged 메서드란,  name 에 해당하는 이름을 갖는 데이터에 변화가 생길때마다 이벤트를 발생시키는 메서드이다.

 

4.   변수의 set 접근자 안에 OnPropertyChanged 메서드를 호출한다.

 

- 변수의 set 접근자 안에 밑의 코드를 넣는다.

 

OnPropertyChanged("변수이름");

- 예시코드입니다. 그럼 예를들어 product 이름이 바꼈을 경우 OnPropertyChanged()가 호출되어 이벤트 발생시킨다

5.   Xaml에 TwoWay-binding 하기

- xaml 에서 Text="{Binding 바인딩시킬 데이터 이름 , UpdateSourceTrigger=PropertyChanged}" 을 넣는다. 그러면 사용자가 예를들어 관리자의 이름을 변경했을 경우 바로 Property가 Changed 된다.

- 코드 예시

 

[ 참고자료 ]

 

INotifyPropertyChanged 구현시 참고한 사이트

 https://docs.microsoft.com/ko-kr/dotnet/framework/wpf/data/how-to-implement-property-change-notification

- https://docs.microsoft.com/ko-kr/dotnet/framework/wpf/data/how-to-control-when-the-textbox-text-updates-the-source

 

TwoWay,OneWay 등등의 개념 잡을 때 참고한 사이트

https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.data.bindingmode?view=netframework-4.8#System_Windows_Data_BindingMode_TwoWay

반응형

[ 목표 ] 

wpf changing visibility from code behid

 

[ 소스코드 ] 

 

xaml

<DataGrid  x:Name="Datagrid_1" Grid.Row="" Grid.Column="" Orientation="Horizontal" Visibility="Visible"  >
	<RadioButton x:Name="rdo_Button1" Content="" VerticalAlignment="Center" IsChecked="True" />
</DataGrid>
<DataGrid x:Name="Datagrid_2" Grid.Row="" Grid.Column="" Orientation="Horizontal" Visibility="Hidden">
	<RadioButton x:Name="rdo_Button2" Content="" VerticalAlignment="Center" IsChecked="True"/>
</DataGrid>

xaml.cs

public Visibility( )
{
	InitializeComponent();
    
    	if (...)
    	{
      	this.Datagrid_1.Visibility = System.Windows.Visibility.Hidden;
      	this.Datagrid_2.Visibility = System.Windows.Visibility.Visible;
    	}            
}        

 

[ 주의할점 ]

 

InitializeComponent( ) 다음에 코드를 넣어야한다.

InitializeComponent( )이란, 간단하게 말해 우리가 만든 xaml 을 불러오는 메소드와 같다고 이해할 수 있다.

이 메소드가 실행되기전에 visibility 값을 변경하는 것은 tv 가 아직 안켜졌는데 채널을 돌리려 리모콘 버튼을 누르는 것과 같다.

반응형

들여올 excel 파일
들여오기 button 클릭 전
들여오기 button 클릭 후

 

[ 방법 ]

1단계 .  들여올 excel 파일 경로 불러오기

2단계 . 가져온 excel 파일 열기

3단계 . excel 파일 안의 원하는 Sheet 에 접근

4단계 . 엑셀의 데이터들을 모델(model)에 담은 후 리스트(list)에 추가하기

5단계 . List에 담겨진 데이터를 Datagrid 에 binding하기

 

[ 소스코드 ]

 

xaml

        <DataGrid x:Name="Datagrid_Import" Grid.Row="1" Grid.ColumnSpan="5" Height="auto" Width="auto" AutoGenerateColumns="False" ItemsSource="{Binding ObserList}" CanUserAddRows = "False" >
                <DataGrid.Resources>
                    <Style TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="Background" Value="#464646"/>
                        <Setter Property="FontWeight" Value="SemiBold" />
                        <Setter Property="BorderThickness" Value="0,0,1,2"/>
                        <Setter Property="BorderBrush" Value="Black"/>
                        <Setter Property="Foreground" Value="White" />
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    </Style>
                </DataGrid.Resources>
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="TextBlock.TextAlignment" Value="Center"/>
                        <Setter Property="IsEditing" Value="true" />
                    </Style>
                </DataGrid.CellStyle>

            <DataGrid.Columns>
                <DataGridTextColumn Header="이름" Width="1.5*" Binding="{Binding ProductName}" IsReadOnly="True"/>
                <DataGridTextColumn Header="수량" Width="*" Binding="{Binding Stock}" IsReadOnly="True"/>
                <DataGridTextColumn Header="제조사" Width="1.5*" Binding="{Binding Manufacture}" IsReadOnly="True"/>
                <DataGridTextColumn Header="입고날짜" Width="2*" Binding="{Binding InputDate, StringFormat = {}{0:yyyy-MM-dd}}" IsReadOnly="True"/>
                <DataGridTextColumn Header="유통기한" Width="2*" Binding="{Binding ExpirationDate, StringFormat = {}{0:yyyy-MM-dd}}" IsReadOnly="True"/>
                <DataGridTextColumn Header="남은기간" Width="1.5*" Binding="{Binding RemainingDate}" IsReadOnly="True"/>
                <DataGridTextColumn Header="관리자" Width="1.5*" Binding="{Binding ManagerNum,Converter={StaticResource ManagerNameConver}}" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>        

        <!-- 하단 Export 버튼-->
        <Button x:Name="btn_Import" Grid.Row="2" Grid.Column="4"  Margin="10" Content="들여오기"  Width="95" Height="40"  Background="Gray" HorizontalAlignment="Left" FontWeight="ExtraBold" Foreground="White" Click="Btn_Import_Click"/>

            <!-- 검색창-->
            <StackPanel Grid.ColumnSpan="5" Grid.Row="0" Orientation="Horizontal"  HorizontalAlignment="Center" >
            <Label Width="75" Height="40" Content="파일 이름"  FontSize="15" HorizontalContentAlignment="Center"  VerticalContentAlignment="Center"/>
            <TextBox x:Name="textbox_FileSearch" Width="500" Height="30" TextWrapping="Wrap" VerticalContentAlignment="Center" />
            <Button x:Name ="btn_FileSearch" Content="파일찾기" Height="30" Width="75" Margin="10" FontWeight="ExtraBold" Click="Btn_FileSearch_Click"  />
            </StackPanel>

xaml.cs

        private void Btn_Import_Click(object sender, RoutedEventArgs e)
        {
            // 파일 경로 불러오기
            var fi = new FileInfo(this.textbox_FileSearch.Text);

            //가져온 파일 열기
            using (var package = new ExcelPackage(fi))
            {
                var workbook = package.Workbook;

                //Excel 안의 AllSheet에 접근
                var worksheet = workbook.Worksheets.FirstOrDefault();

                // 시트의 마지막 Row 데이터에서 1빼기
                int noOfRow = worksheet.Dimension.End.Row - 1;

                // 종류 row를 제외하고 2부터 시작하기
                int row = 2;
                List<mProduct> excelData = new List<mProduct>();
                for (int k = 0; k <= noOfRow - 1; k++)
                {
                    mProduct item = new mProduct();
                    item.ProductNumber = Convert.ToInt32(worksheet.GetValue(row, 1));
                    item.ProductName = worksheet.GetValue(row, 2).ToString();
                    item.Stock = Convert.ToInt32(worksheet.GetValue(row, 3));
                    item.Manufacture = worksheet.GetValue(row, 4).ToString();
                    item.InputDate = Convert.ToDateTime(worksheet.GetValue(row, 5).ToString());
                    item.ExpirationDate = Convert.ToDateTime(worksheet.GetValue(row, 6).ToString());
                    item.RemainingDate = Convert.ToInt32(worksheet.GetValue(row, 7));
                    item.ManagerNum = Convert.ToInt32(worksheet.GetValue(row, 8));
                    row++;
                    excelData.Add(item);

                    // productNumber가 0인 시점에서 데이터 불러오는 작업 중단하기
                    if (Convert.ToInt32(worksheet.GetValue(row, 1)) == 0)
                    { break; }
                }
                this.Datagrid_Import.ItemsSource = excelData;
            }
        }

 

반응형

+ Recent posts