开发者

How do I use a code behind property in a trigger to change a control property?

开发者 https://www.devze.com 2022-12-23 17:26 出处:网络
I am trying to do a fairly simple thing in my WPF application, or at least I think it\'s simple. I have a Window that contains an int property in the code behind. Let\'s call this one IntProperty. Th

I am trying to do a fairly simple thing in my WPF application, or at least I think it's simple.

I have a Window that contains an int property in the code behind. Let's call this one IntProperty. The Window implements the INotifyPropertyChanged interface and IntProperty fires the notification on change. It looks like this:

        public int IntProperty
    {
        get
        {
            return intProperty;
        }

        private set
        {
            if (value != intProperty)
            {
                intProperty = value;
                NotifyPropertyChanged("IntProperty");
            }
        }
    }

In the xaml file I have defined a Rectangle with a specifid color set in the Fill property.

                    <Rectangle x:Name="MyRectangle" Fill="Red" Width="100" Height="5" Margin="3,0,0,0" VerticalAlignment="Center" />

What I want to do now is to set the Fill property depending on the value of IntProperty. I'm looking for a few simple xaml lines that trigger this change.

It should look like this (AppWindow is the name of the Window):

<Rectangle x:Name="MyRectangle" Fill="Red" Width="100" Height="5" Margin="3,0,0,0" VerticalAlignment="Center">
<Rectangle.Triggers>
    <Trigger SourceName="AppWindow" Property="IntProperty" Value="1">
        <Setter TargetName="MyRectangle" Property="Fill" Value="Green" />
    </Trigger>
</Rectangle.Triggers>

Is there any easy way to do this? So far I couldn't fi开发者_StackOverflownd any simple solution to this. I would appreciate it, if someone could point me in the right direction.

Thanks!


You'll want to use a DataTrigger for this.

<Rectangle x:Name="MyRectangle" Fill="Red" Width="100" Height="5" Margin="3,0,0,0" VerticalAlignment="Center">
    <Rectangle.Triggers>
        <DataTrigger Binding="{Binding IntProperty}" Value="1">
            <Setter TargetName="MyRectangle" Property="Fill" Value="Green" />
        </Trigger>
    </Rectangle.Triggers>
</Rectangle>
0

精彩评论

暂无评论...
验证码 换一张
取 消