在XAML中有类似于循环的东西

时间:2013-11-23 18:09:31

标签: wpf xaml

我有一个资源字典,我希望在其中有一个共同的DataTemplate for ComboBox。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate DataType="{x:Type ComboBox}">
        <StackPanel Orientation="Horizontal">
            <!--Here I need to use something like For Loop-->
            <TextBlock Text=""></TextBlock>
        </StackPanel>
    </DataTemplate>
</ResourceDictionary>

现在我创建了一个名为NoOfColumns的整数类型的依赖项属性。在声明comboBox时,我需要设置NoOfColumns属性以自动生成该列数。我希望他们databind

根据Joe的要求进行更新

<ComboBox x:Name="cbUnder" ItemsSource="{Binding GroupsAndCorrespondingEffects}" 
    IsEditable="True" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}" 
    Text="{Binding InputValue, UpdateSourceTrigger=PropertyChanged}" TextSearch.TextPath="GroupName" 
    Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3">
    <ComboBox.Resources>
        <DataTemplate DataType="{x:Type vm:GroupAndCorrespondingEffect}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding GroupName}" Width="250">
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsHighlighted}" Value="True">
                                    <Setter Property="Foreground" Value="Blue" />
                                    <Setter Property="FontWeight" Value="Bold"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
                <TextBlock Text="{Binding CorrespondingEffect}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.Resources>
</ComboBox>

1 个答案:

答案 0 :(得分:4)

XAML中没有for,但ItemsControlforeach非常相似。不要设置int属性,而是创建ObservableCollection<T>并向其添加许多对象,然后将ItemsControl绑定到您的集合属性。

这具有额外的好处,即每个集合项可以暴露要绑定的属性,例如,如果要在每个TextBlock中显示不同的文本,可以在集合项上放置一个属性,并将TextBlock绑定到该属性。

相关问题