如何将DataTrigger绑定到Interface属性

时间:2011-06-21 20:32:31

标签: c# wpf xaml .net-4.0 datatrigger

我有4个类来实现我的自定义ICalendarItem接口。 该界面有一个名为'Jours'的属性。

ObservableCollection<KeyValuePair<DateTime, DateTime>> Jours;

我的类覆盖了这样的属性:

public override ObservableCollection<KeyValuePair<DateTime, DateTime>> Jours {...}

当Jours.Count从0变为1时,我想触发一个动作,所以我尝试了这个:

<DataTrigger Binding="{Binding Path=Jours.Count}" Value="1">

<DataTrigger Binding="{Binding Path=(ICalendarItem)Jours.Count}" Value="1">

这两个DataTrigger都不起作用。

任何人都知道如何将DataTrigger绑定到Interface属性?

2 个答案:

答案 0 :(得分:2)

如果要特定绑定到自定义接口属性,则需要将命名空间,接口和属性名称放在括号内。然后,您可以在括号外引用像Count这样的子属性。

<DataTrigger Binding="{Binding Path=(local:ICalendarItem.Jours).Count}" Value="1">
...
</DataTrigger>

答案 1 :(得分:1)

在我的测试中,它的工作做得很好。请参考以下代码,这可能对您有所帮助。

这段代码的作用是,当`Jours.Count'等于“3”时,Window背景变为红色。 XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Jours.Count}" Value="3">
                    <Setter Property="Control.Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
    </Grid>
</Window>

代码隐藏:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ITest test = new TestClass();
        this.DataContext = test;
    }
}

interface ITest
{
    ObservableCollection<KeyValuePair<DateTime, DateTime>> Jours { get; set; }
}

class TestClass : ITest
{
    public TestClass()
    {
        Jours = new ObservableCollection<KeyValuePair<DateTime, DateTime>>();
        Jours.Add(new KeyValuePair<DateTime, DateTime>(DateTime.Now, DateTime.Now));
        Jours.Add(new KeyValuePair<DateTime, DateTime>(DateTime.Now, DateTime.Now));
        Jours.Add(new KeyValuePair<DateTime, DateTime>(DateTime.Now, DateTime.Now));
    }

    public ObservableCollection<KeyValuePair<DateTime, DateTime>> Jours { get; set; }
}