보통 컨트롤을 찾을땐 그냥 this.grid1 이렇게 찾는다 하지만
컬렉션안이라든지 DataTemplate 안에서는 찾기가 에메하다 이때는 VisualTreeHelper 를 이용해서찾으면된다.
private void button1_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
//버튼을 기준으로 border1 을 찾고있다.
Border b = FindVisualParentByName<Border>(btn, "border1");
b.Background = this.Resources["Brush2"] as Brush;
//border1 을 기준으로 버튼을 찾고 있다.
Button FindBtn = FindVisualChildByName<Button>(this.border1, "button2");
FindBtn.Background = this.Resources["Brush2"] as Brush;
}
/// <summary>
/// 자신의 컨트롤 한단계 위부터 사용자정의 이름으로 검색합니다.
/// </summary>
/// <typeparam name="T">결과값의 형식</typeparam>
/// <param name="_Control">검색을 시작할 컨트롤</param>
/// <param name="_FindControlName">찾고자하는 컨트롤 이름</param>
/// <returns></returns>
private T FindVisualParentByName<T>(FrameworkElement _Control, string _FindControlName) where T : FrameworkElement
{
T t = null;
DependencyObject obj = VisualTreeHelper.GetParent(_Control); //오브젝트검사
for (int i = 0; i < 100; i++) //최대 100개의 컨트롤 까지 검색
{
string currentName = obj.GetValue(Control.NameProperty) as string;
if (currentName == _FindControlName)
{
t = obj as T;
break;
}
obj = VisualTreeHelper.GetParent(obj); //1번 오브젝트 부모니깐 2번오브젝트 불러오기 계속 이런씩으로 검색
if (obj == null) //더이상 검사할 컨트롤 없다 빠져 나가자 ㅡ_ㅡ
{
break;
}
}
return t;
}
/// <summary>
/// 자신의 컨트롤 한단계 아래부터 사용자정의 이름으로 검색합니다.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="_Control"></param>
/// <param name="_FindControlName"></param>
/// <returns></returns>
private T FindVisualChildByName<T>(DependencyObject _Control, string _FindControlName) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(_Control); i++)
{
var child = VisualTreeHelper.GetChild(_Control, i);
string controlName = child.GetValue(Control.NameProperty) as string;
if (controlName == _FindControlName)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, _FindControlName);
if (result != null)
{
return result;
}
}
}
return null;
}'WPF' 카테고리의 다른 글
| [WPF Ribbon 컨트롤] Windows Xp 오류 문제 (0) | 2010.12.17 |
|---|---|
| [DataGridCell / Setter ] 특정 Cell 만 변경하기 (0) | 2010.11.26 |
| [WPF Blend4/MouseDrag/MouseDragElementBehavior ] 창 가운데 띄우기 / 마우스드래그 (0) | 2010.11.24 |
| WPF Dialog Box/ ValidationRule 파일열기 유효성검사 (0) | 2010.10.20 |
| [ADO.NET Entity Data Model ]실버라이트 초간단 데이터 바인딩 (0) | 2010.10.14 |
| [DependencyObject.GetValue] 사용하기 (0) | 2010.09.16 |
| [Blend4 / DataGrid / DataTemplate / CellEditingTemplate / Edit] 데이터그리드 편집모드 사용하기 (0) | 2010.09.16 |
| StaticResource 와 DynamicResource 의 차이 (0) | 2010.09.15 |
| [StringFormat] 초간단 날짜 표시방법변경 (0) | 2010.09.01 |
| [NavigationService / PageFunction] 페이지 이동 (2) | 2010.08.23 |