Nat Luengnaruemitchai

Geek Blog

  Home  |   Contact  |   Syndication    |   Login
  100 Posts | 0 Stories | 300 Comments | 232 Trackbacks

News

Archives

Post Categories

Blogroll

Yesterday, I had a problem where I need to hook up an event to a certain data condition. I first thought about EventTrigger. However, it does the other way around. This class is responsible for convert event into trigger. So I digged around WPF architecture to see what I can do and bingo. I found that I can create an attached property with the following construct

 

 

 

 

and then in XAML, you can register for this event by

<TextBox Text="Try me">
    <
TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <
Style.Triggers>
                <
Trigger Property="Text" Value="Cool">
                    <
Setter Property="me:Window1.SomethingHappened" Value="True" />
                </
Trigger>
            </
Style.Triggers>
        </
Style>
    </
TextBox.Style>
</
TextBox>

 

public static readonly DependencyProperty SomethingHappenedProperty = DependencyProperty.RegisterAttached("SomethingHappened",typeof(bool),typeof(Window1),new PropertyMetadata(false,new PropertyChangedCallback(SomethingHappened)));public bool GetSomethingHappened(DependencyObject d)
{
    return (bool)d.GetValue(SomethingHappenedProperty);
}
public void SetSomethingHappened(DependencyObject d, bool value)
{
    d.SetValue(SomethingHappenedProperty, value);
}
private void SomethingHappened(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // do something here
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Thursday, September 20, 2007 7:55 AM

Feedback

# re: WPF: Transform trigger into event 5/19/2009 5:44 PM bob
This does not seem to work for me.

Firstly the method "private void SomethingHappened(DependencyObject d, DependencyPropertyChangedEventArgs e)" needs to be a static method because the attached property is static.

Secondly, the resolution to the attached property SomthingHappened (<Setter Property="me:Window1.SomethingHappened" Value="True" /> ) does not seem to want to work as I keep getting an error saying that it cannot find the Style Property SomethingHappened...



# re: WPF: Transform trigger into event 4/5/2011 6:05 AM anon
This shit doesn't work

# re: WPF: Transform trigger into event 4/5/2011 6:09 AM anon
Sorry. It work. You should write <Setter Property="me:YourClassName.YourDependencyPropertyName"


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: