Как да нарисувате конкретни редове в списъчно поле (WPF приложение)

Пиша проект, който включва WPF прозорец, който съдържа списък. списъкът използва обвързване към списък със задачи (клас, който създадох). Опитвам се да нарисувам някои конкретни редове от списъчната кутия и някои конкретни редове да имат цветни граници въз основа на полетата на елементите в списъка. как да добавя метод за рисуване/четка за конкретни редове към списъчно поле, а не за целия списък? По-долу са XAML свойствата на списъчната кутия:

<ListBox Name="Tasks" HorizontalAlignment="Left" ItemsSource="{Binding Path=Tasks,Mode=TwoWay}" Height="199" Margin="303,97,0,0" VerticalAlignment="Top" Width="439" RenderTransformOrigin="0.5,0.5">
            <ListBox.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="0.294"/>
                    <TranslateTransform/>
                </TransformGroup>
            </ListBox.RenderTransform>
        </ListBox>

person George    schedule 02.06.2020    source източник
comment
Това отговаря ли на въпроса ви Елемент от списъчно поле WPF, различен цвят на фона за различни елементи   -  person neelesh bodgal    schedule 02.06.2020
comment
ListBox.ItemContainerStyle - предоставя персонализиран стил за ListBoxItems в това свойство. Можете да зададете BorderBrush и Background на ListBoxItems   -  person ASh    schedule 02.06.2020


Отговори (1)


ItemsControl има специална функция за избор на шаблони за елементи, показани в контролата. В следващия пример илюстрирам използването на DataTemplateSelector

Първо XAML. В секцията Ресурси са дефинирани различни шаблони на данни за различните типове елементи, които искате да покажете в ListBox, и има препратка към DataTemplateSelector (дефиниран в C# кода по-късно):

<Window x:Class="TestWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpfApp"
        mc:Ignorable="d"
        x:Name="DataWindow"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
   <Window.Resources>
      <!-- The data template selector -->
      <local:DataItemTemplateSelector x:Key="DataItemTemplateSelector"/>
      <!-- Data template for a normal data item -->
      <DataTemplate x:Key="NormalDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="White"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Transparent">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
      <!-- Data template for a special data item -->
      <DataTemplate x:Key="SpecialDatatemplate">
         <Border Width="200"
                 Margin="0"
                 Background="Yellow"
                 BorderThickness="2"
                 Padding="3"
                 BorderBrush="Blue">
            <TextBlock VerticalAlignment="Center"
                       HorizontalAlignment="Stretch"
                       FontSize="20"
                       Foreground="Black"
                       Background="Transparent"
                       Text="{Binding Path=Header}"/>
         </Border>
      </DataTemplate>
   </Window.Resources>
   <Grid>
      <ListBox x:Name="DataListBox"   
               Margin="50"
               Width="Auto"
               Height="Auto"
               HorizontalAlignment="Center"
               VerticalAlignment="Top"
               ItemsSource="{Binding ElementName=DataWindow, Path=DataList}"
               ItemTemplateSelector="{StaticResource ResourceKey=DataItemTemplateSelector}"/>
   </Grid>
</Window>

И след това кодът на C#, там DataItemTemplateSelector е дефиниран и DataList с някои тестови данни:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace TestWpfApp
{
   // Different types of items on the list
   public enum DataItemType
   {
      Normal,
      Special
   }
   // Items on the list
   public class DataItem
   {
      public string Header { set; get; }
      public DataItemType DataType { set; get; }
   }
   // Data template selector for items on the list
   public class DataItemTemplateSelector : DataTemplateSelector
   {
      public override DataTemplate SelectTemplate(object dataItem, DependencyObject container)
      {
         // Check that everyting is OK
         if ((dataItem != null) && (dataItem is DataItem))
         {
            // Switch on the data type
            switch (((DataItem)(dataItem)).DataType)
            {
               case DataItemType.Normal:
                  // Return the data template for a normal data item 
                  return Application.Current.MainWindow.FindResource("NormalDatatemplate") as DataTemplate;
               case DataItemType.Special:
                  // Return the data template for a special data item 
                  return Application.Current.MainWindow.FindResource("SpecialDatatemplate") as DataTemplate;
               default:
                  return null;
            }
         }
         return null;
      }
   }
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      // The list of data to show in the list box
      public List<DataItem> DataList { set; get; }
      // The constructor of the main window
      public MainWindow()
      {
         // Some test data
         this.DataList = new List<DataItem>();
         this.DataList.Add(new DataItem() { Header = "Item 1", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 2", DataType = DataItemType.Normal });
         this.DataList.Add(new DataItem() { Header = "Item 3", DataType = DataItemType.Special });
         this.DataList.Add(new DataItem() { Header = "Item 4", DataType = DataItemType.Normal });
         // Initializing the window
         InitializeComponent();
      }
   }
}

Надявам се, че схванахте идеята за използване на DataTemplateSelector и след това можете да стилизирате своя ListBox и различните типове елементи в него

person Anders H    schedule 02.06.2020