Geeks With Blogs
Nat Luengnaruemitchai Geek Blog

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
}
Posted on Thursday, September 20, 2007 7:55 AM WPF | Back to top


Comments on this post: WPF: Transform trigger into event

# re: WPF: Transform trigger into event
Requesting Gravatar...
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...

Left by bob on May 19, 2009 5:44 PM

# re: WPF: Transform trigger into event
Requesting Gravatar...
This shit doesn't work
Left by anon on Apr 05, 2011 6:05 AM

# re: WPF: Transform trigger into event
Requesting Gravatar...
Sorry. It work. You should write <Setter Property="me:YourClassName.YourDependencyPropertyName"
Left by anon on Apr 05, 2011 6:09 AM

Your comment:
 (will show your gravatar)
 


Copyright © Nat Luengnaruemitchai | Powered by: GeeksWithBlogs.net | Join free