wpf 类似于 XAML 中的 For 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20165982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Something Like For Loop in XAML
提问by Khushi
I have a Resource Dictionary in which I want to have a common DataTemplate for ComboBox.
我有一个资源字典,我想在其中为 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>
Now I have created a dependency property of type integer named NoOfColumns. While declaring the comboBox I need to set the NoOfColumns property to automatically generate that number of columns. I want them to databind.
现在我创建了一个名为 NoOfColumns 的整数类型的依赖属性。在声明组合框时,我需要设置 NoOfColumns 属性以自动生成该数量的列。我想让他们databind。
Update as requested by 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>
回答by Joe White
There's nothing like forin XAML, but ItemsControlis very much like foreach. Instead of setting an intproperty, make an ObservableCollection<T>and add that many objects to it, and then bind the ItemsControlto your collection property.
forXAML 中没有任何东西,但ItemsControl非常类似于foreach. 而不是设置一个int属性,而是创建一个ObservableCollection<T>并向其添加那么多对象,然后将 绑定ItemsControl到您的集合属性。
This has the added benefit that each collection item can expose properties to be bound, e.g. if you wanted to display different text in each TextBlock, you could put a property on your collection item and bind the TextBlockto that property.
这有一个额外的好处,即每个集合项都可以公开要绑定的属性,例如,如果您想在每个 中显示不同的文本TextBlock,您可以在您的集合项上放置一个属性并将 绑定TextBlock到该属性。

