簡體   English   中英

如何使此顯示用於列表框?

[英]How could I make this display for listbox?

我有一個數據綁定列表框,它實際上在顯示兩列數據。 顯示如下:

<UserControl.Resources>
        <DataTemplate x:Key="AlignedPairs">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="10" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Fruits}" Grid.Column="0" />
                <TextBlock Text="->" TextAlignment="Center" Grid.Column="1" />
                <TextBlock Text="{Binding Colors}" Grid.Column="3" />
            </Grid>
        </DataTemplate>
    </UserControl.Resources>

            <ListBox Name="lbStuff" Grid.ColumnSpan="2"  Grid.Row="1"
                     ItemTemplate="{StaticResource AlignedPairs}">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    </Style>
                </ListBox.ItemContainerStyle>
            </ListBox>

然后在代碼源中設置Itemsource。

但是,基於某種邏輯,我想在其中一列中設置一行或一項,例如,將水果設置為紅色,或將行設置為粗體。 我有代碼可以在后面的代碼中找出要區分(按顏色/粗體顯示)哪種水果或顏色,但是我不知道,特別是考慮到自定義列表框顯示后,我該如何設置特定項目更改為其他顏色/粗體。

有人有什么想法嗎?

讓我知道是否需要其他代碼。 干杯。

編輯:我真正想做的就是讓問題盡可能的容易...遍歷列表框中的每個項目,並使用字符串進行檢查,如果有匹配項,SOMEHOW可以在視覺上區分出列表框中/列表視圖中的該項目。 無需使其變得比所需的復雜。 為什么您不能單獨設置項目前景色呢?

編輯2:

看起來我幾乎可以通過以下操作到達那里(但是它會引發異常並且不起作用)

            foreach (var li in ListView.Items)
            {

                if (someCriteria == true) 
                {
                      ((ListViewItem) li).Foreground = Brushes.Red; 
//exception throw as this is the actual object stored in this location (the Fruit object for example) not the row or listviewitem I want to change the color of so it can't be cast :(
                }
            }

這是ViewModel設計模式真正為您提供幫助的地方。

大概您有一個公開了FruitColor屬性的類。 創建一個包裝器類,該類同時公開這些屬性,並公開FruitBackgroundBrushItemBackgroundBrush 然后,您可以綁定到模板中的那些屬性,例如:

<DataTemplate x:Key="AlignedPairs">
    <Grid Background={Binding ItemBackgroundBrush}>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="10" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Fruits}" 
                   Background="{Binding FruitBackgroundBrush}" 
                   Grid.Column="0" />
        <TextBlock Text="->" TextAlignment="Center" Grid.Column="1" />
        <TextBlock Text="{Binding Colors}" Grid.Column="3" />
    </Grid>
</DataTemplate>

DataTriggers將解決此問題。 這是一個很好的入門手冊: http : //en.csharp-online.net/WPF_Styles_and_Control_Templates%E2%80%94Data_Triggers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM