본문 바로가기

프로그래밍/C#, WPF, Winform

C# WPF DataGrid에 UserControl을 넣고 UserControl에서 원하는 동작을 하기





XAML

1
2
3
4
5
6
7
8
9
10
11
<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Message" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <local:UserControl1/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
cs

 

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Windows;
using System.Windows.Controls;
 
namespace TestProject.Controls
{
    public partial class UserControl1: UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
 
            this.DataContextChanged += UserControl1_DataContextChanged;
        }
 
        private void UserControl1_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            //Do Something with e.NewValue
        }
    }
}
 
cs