我有一个仅绑定(bind)到集合的列表框。该集合有一个子集合 (StepDatas)。我想绑定(bind)到子集合的计数,但使用 WHERE 语句。我可以绑定(bind)到 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>
以上代码用于绑定(bind)到子集合的计数。不过,我希望显示满足特定条件的子集合的计数。在这种特定情况下,子集合具有完整的属性 (bool)。所以...我想显示计数 StepDatas.Where(x => x.Completed == true).Count。
这有可能吗?感谢您的帮助!
最佳答案
对主题问题的简短回答是:不。
明智的答案是:确保您需要的Count
可作为数据模型的属性使用。例如,确保 StepDatas
公开的类型具有 Count
属性。
但是,您确实用“以任何方式可能?”来限定这一点。可以绑定(bind)到 ListItem 数据上下文并使用一些疯狂的值转换器来执行 lambda。然而,为了简单起见,您需要专门为您的 lambda 创建一个转换器。 转换器代码如下所示:-
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 的 Resources 属性中创建此转换器的实例,为方便起见,可以在 UserControl 中使用:-
<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>
现在在您的绑定(bind)中:-
<TextBlock Text="{Binding Converter={StaticResource Counter} }" ... >
关于silverlight - 是否可以绑定(bind)到 Silverlight 中的 lambda 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1510304/