是否可以绑定到在Silverlight lambda表达式?(Is it possible to b

2019-08-17 04:30发布

我有一个简单的结合集合的列表框。 收集有一个孩子集合(StepDatas)。 我想结合给孩子收集的计数,但用WHERE语句。 我可以绑定到ChildCollection.Count但需要添加的lambda表达式时迷路。 这里的XAML:

<ListBox Height="Auto" Style="{StaticResource ListBoxStyle1}" Margin="4,46,4,4" x:Name="lstLeftNavigation" Background="{x:Null}" SelectionChanged="lstLeftNavigation_SelectionChanged">
<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid Width="180" Margin="2,2,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" d:LayoutOverrides="Width" MinHeight="36">
            <TextBlock Text="{Binding StepNm}" x:Name="tbStepNm" Margin="10,0,34,0" TextWrapping="Wrap" FontFamily="Portable User Interface" Foreground="White" FontSize="10" FontWeight="Bold" VerticalAlignment="Center"/>
            <Image Height="37" HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center"  Width="37" Source="Images/imgIcoChecked.png" Stretch="Fill"/>
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>

上述工作结合到子集的数量。 但是我想表明孩子集合,其中一个满足特定条件的计数。 在这种特殊情况下,孩子集合有一个已建成物业(布尔)。 所以...我想显示计数StepDatas.Where(X => x.Completed ==真).Count之间。

这是在任何可能的方式? 谢谢你的帮助!

Answer 1:

简短的回答主体的问题是:没有。

明智的回答是:确保Count则需要由数据模型可用的属性。 例如,确保暴露类型StepDatas具有Count属性。

然而,你用“在任何可能的方式?”这个资格。 它可以绑定到列表项数据的上下文,并使用一些值转换器疯狂来执行你的拉姆达。 然而,为了让事情变得简单,你需要创建一个特定的转换器为你的拉姆达。 下面是转换代码是这样: -

 public class CountCompletedStepDatas : IValueConverter
 {

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      YourItemsType item = (YourItemsType)value;
      return item.StepDatas.Were(x => x.Completed == true).Count().ToString(culture);
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }

你会在做这个转换器在XAML一个资源属性缴费的一个实例,说方便的用户控件: -

<UserControl x:Class="YourNameSpace.ThisControlName"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:YourNameSpace;assembly=YourAssemblyName">
  <UserControl.Resources>
    <local:CountCompletedStepDatas x:Key="Counter" />
  </UserContro.Resources>

现在,在你的绑定: -

 <TextBlock Text="{Binding Converter={StaticResource Counter} }" ... >


Answer 2:

感谢您的答复。 提交问题后,我写了一个转换器类做你结束了提示,但发现Count属性不会导致重新绑定,当数据发生变化的。 这将强制的情况下,我们将不得不手动更新绑定时更改。 为了更新目标获取列表框内部的图像对象的引用是unforntunately在一个痛苦的屁股!

最终,我只是增加了一个新的字段的数据源,并直接绑定的形象像你的建议。 干净多了。

感谢您的建议! 道格



文章来源: Is it possible to bind to a lambda expression in Silverlight?