wpf - 如何在触发器中使用代码隐藏属性来更改控件属性?

标签 wpf xaml properties triggers

我试图在我的 WPF 应用程序中做一件相当简单的事情,或者至少我认为它很简单。

我有一个窗口,在后面的代码中包含一个 int 属性。我们将其称为 IntProperty。 Window 实现 INotifyPropertyChanged 接口(interface),并且 IntProperty 在更改时触发通知。它看起来像这样:

        public int IntProperty
    {
        get
        {
            return intProperty;
        }

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

在 xaml 文件中,我定义了一个矩形,并在 Fill 属性中设置了指定的颜色。

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

我现在要做的是根据 IntProperty 的值设置 Fill 属性。 我正在寻找一些触发此更改的简单 xaml 行。

它应该看起来像这样(AppWindow是窗口的名称):

<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>

有什么简单的方法可以做到这一点吗?到目前为止我找不到任何简单的解决方案。如果有人能指出我正确的方向,我将不胜感激。

谢谢!

最佳答案

您需要使用 DataTrigger为此。

<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>

关于wpf - 如何在触发器中使用代码隐藏属性来更改控件属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2501615/

相关文章:

c# - 将 DataGrid 单元格绑定(bind)到索引属性

c# - 了解对象中的属性类型 C#

Swift 类属性更新

iphone - 如何编写正确的只读属性?

wpf - 如何在其中心设置 DXRibbonWindow 的标题

.net - WPF 动态资源示例

c# - 在我需要基于 XAML 控件进行计算的情况下,使用 MVVM 与控件交互的正确设计是什么?

c# - Windows Phone 8 绑定(bind)到具有格式的字符串资源

c# - 未找到具有显式 ElementName 的 WPF DataBinding

c# - 将 DateTime 绑定(bind)到日期和时间 EditFields