我有一个绑定到类的WPF ListBox。如下
public class MyClass
{
public string Name{ get; set; }
public string Gender{ get; set; }
}
ObservableCollection<MyClass> myData= new ObservableCollection<MyTable>();
myClassList.ItemsSource = myData;
我将XAML视为:
<DataTemplate x:Key="userData">
<Grid HorizontalAlignment="Stretch" Margin="3,0,3,0" Height="60">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<wpfgeneralcontrols:TextControl Grid.Column="0" Grid.Row="0" Text="{Binding Path=Name}" Style="{StaticResource SmallTextControlStyle}"
TextAlignment="Left" Margin="0"/>
<wpfgeneralcontrols:TextControl Grid.Column="1" Grid.Row="0" Text="{Binding Path=Gender}" Style="{StaticResource SmallTextControlStyle}"
TextAlignment="Left" Margin="0"/>
</Grid>
</DataTemplate>
<ListView Name="PatientsList" Background="Transparent" BorderThickness="0"
Width="700" HorizontalAlignment="Center"
ItemTemplate="{StaticResource userData}"
ScrollViewer.VerticalScrollBarVisibility ="Visible" />
如何仅设置ListBox的第一项(不是所选项目)的前景色?我已经看到了一些关于接近这个的想法,但无法使其适应设置列表框中第一个项目的前景色。
答案 0 :(得分:1)
您不能在纯XAML中执行此操作 - XAML是标记语言而不是编程语言 - 但您可以处理根Loaded
的{{1}}事件在您的Grid
中以编程方式:
ItemTemplate
<DataTemplate x:Key="userData">
<Grid HorizontalAlignment="Stretch" Margin="3,0,3,0" Height="60"
Loaded="Grid_Loaded">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding Path=Name}"
TextAlignment="Left" Margin="0"/>
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding Path=Gender}"
TextAlignment="Left" Margin="0"/>
</Grid>
</DataTemplate>
我认为您的自定义int n = 0;
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
if (n++ == 0)
{
Grid grid = sender as Grid;
foreach (var tb in grid.Children.OfType<TextBlock>())
tb.Foreground = System.Windows.Media.Brushes.Red;
grid.Loaded -= Grid_Loaded;
}
}
具有TextControl
属性。在上面的示例代码中,我使用了Foreground
。
这并没有打破MVVM模式。在视图中实现与视图相关的逻辑是完全正确的。
答案 1 :(得分:0)
如果您的商品不为空,则可以使用PreviousData
来检测第一项。
<DataTemplate x:Key="userData">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
<ListView ItemTemplate="{StaticResource userData}" ItemsSource="{Binding MyItems}">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
</ListView>