我有一个资源字典,我想在其中为 ComboBox 提供一个通用的 DataTemplate。
<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>
Run Code Online (Sandbox Code Playgroud)
现在我创建了一个名为 NoOfColumns 的整数类型的依赖属性。在声明组合框时,我需要设置 NoOfColumns 属性以自动生成该数量的列。我想让他们databind。
应乔的要求更新
<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>
Run Code Online (Sandbox Code Playgroud)
forXAML 中没有任何东西,但ItemsControl非常类似于foreach. 而不是设置一个int属性,而是创建一个ObservableCollection<T>并向其添加那么多对象,然后将 绑定ItemsControl到您的集合属性。
这有一个额外的好处,即每个集合项都可以公开要绑定的属性,例如,如果您想在每个 中显示不同的文本TextBlock,您可以在您的集合项上放置一个属性并将 绑定TextBlock到该属性。