Dependency Property 중에 다른 하나인 Attached Property 를 정리해 봅니다.
1. Declare Attached Property Class
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace SteveDependencyProperties.AttachedProperties
{
/// <summary>
/// AttachedProperty class declare
/// </summary>
public static class MyTestAttachedProperties
{
/// <summary>
/// DependencyProperty.RegisterAttached
/// </summary>
public static readonly DependencyProperty ShowCommonWinodwButtonProperty =
DependencyProperty.RegisterAttached(
"ShowCommonWinodwButton",
typeof(bool),
typeof(MyTestAttachedProperties),
new PropertyMetadata(false, Changed));
/// <summary>
/// Attached Property Call Back Event
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var button = d as Button;
if (button == null) return;
if(e.NewValue != null && (bool)e.NewValue)
{
button.Click += ButtonClick;
}
else
{
button.Click -= ButtonClick;
}
}
/// <summary>
/// Receive Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void ButtonClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("ShowCommonWinodwButtonAttachedProperty");
}
/// <summary>
/// Attached Set Property
/// </summary>
/// <param name="element"></param>
/// <param name="value"></param>
public static void SetShowCommonWinodwButton(UIElement element, bool value)
{
element.SetValue(ShowCommonWinodwButtonProperty, value);
}
/// <summary>
/// Attached Get Property
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static bool GetShowCommonWinodwButton(UIElement element)
{
return (bool)element.GetValue(ShowCommonWinodwButtonProperty);
}
}
}
2. Using XAML
<Window x:Class="SteveDependencyProperties.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:attachedDependency="clr-namespace:SteveDependencyProperties.AttachedProperties" <-(1)
Title="MainWindow" Height="350" Width="525">
<Grid>
<WrapPanel>
<TextBlock>MyTestDependency</TextBlock>
<TextBox Text=" and "></TextBox>
<Button Content="Test Attached Property" attachedDependency:MyTestAttachedProperties.ShowCommonWinodwButton="true"> <-(2)
</Button>
</WrapPanel>
</Grid>
</Window>
3. 정리
(1) 사용을 원하는 XAML에서 Attached Property 를 선언합니다.
(2) 버튼에 개발자가 선언한 Attached Property를 등록합니다. 이렇게 하면 자동으로 버튼 클릭 이벤트를 따로 선언하지 않고 MyTestAttachedProperties 에 있는 버튼 클릭 이벤트가 동작합니다.
출처 : 다년간의 프로그래밍 경험
'C#(CSharp) > WPF' 카테고리의 다른 글
using cefSharp in WPF (0) | 2018.02.13 |
---|---|
ObservableCollection 바인딩(Binding) (0) | 2015.04.08 |
의존 속성(Dependency Object) (0) | 2015.04.08 |
사용자 정의 이벤트 만들기 (0) | 2015.04.08 |
XAML Custom Namespace (0) | 2015.04.08 |