父属性上的DataTrigger

时间:2011-12-12 13:41:48

标签: wpf triggers

如果至少有一个按钮可用,如何正确设置“IsAtLeastOneUserAvailable”依赖项属性?依赖项属性在xaml的代码中设置。所以,我们可以像那样绑定它

  

“{Binding IsAtLeastOneUserAvailable,ElementName = control}”

如果ItemsControl中没有可见的控件,我想隐藏标签。

<UserControl ... Name="control">
<Label Content="Test" Visibility={Binding IsAtLeastOneUserAvailable, ElementName=control">
<ItemsControl ItemsSource="{Binding Users, ElementName=control}" >
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Visibility="{Binding IsAvailable, Converter={StaticResource BooleanToVisibilityConverter}}">
        <Button.Triggers>              
          <DataTrigger Binding="IsAvailable" Value="True">
            <Setter Property="IsAtLeastOneUserAvailable" Value="True" />
          </DataTrigger>
        </Button.Triggers>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Name}"/>
        </StackPanel>
      </Button>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>

1 个答案:

答案 0 :(得分:0)

为什么不根据linq查询在UserControl中设置UserControl.IsAtLeastOneUserAvailable属性,而不是尝试使用触发器设置值?

public bool IsAtLeastOneUserAvailable
{
    get
    {
        return Users.Any(p => p.IsAvailable);
    }
}

您还可以在用户更改的事件中引发此PropertyChanged事件:

public MyUserControl()
{
    Users.CollectionChanged += Users_CollectionChanged;
}

void Users_CollectionChanged(object sender, CollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(User user in e.NewItems)
            user.PropertyChanged += User_PropertyChanged;

    if (e.OldItems != null)
        foreach(User user in e.OldItems)
            user.PropertyChanged -= User_PropertyChanged;
}

void User_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "IsAvailable")
        RaisePropertyChanged("IsAtLeastOneUserAvailable");
}