2015-09-21 2 views
1

У меня есть приложение, подобное Outlook. Есть 3 раздела. Средняя часть содержит ListView. Элементов средней части ListView рассчитали стилиWinRT Xaml Настройка различных стилей на ListViewItems

(красный шрифт = Устаревшая Работа, Bolt Font = непрочитанная Работа, Зачеркнутый текст = Выполненные задания)

. Условия могут пересекаться в разных вариантах.

У меня есть Xaml разметку section2:

 <HubSection Name="Section2" Width="400" DataContext="{Binding Section2Items}" 
        d:DataContext="{Binding Groups[0], Source={d:DesignData Source=../HopUp.Shared/DataModel/SampleData.json, Type=data:SampleDataSource}}" 
        x:Uid="Section2Header" Header="Section 2" Padding="5,25,0,10"> 

      <DataTemplate> 

       <ListView 
        x:Name="lvSection2" 
        ItemsSource="{Binding Items}" 
        Margin="0,-0,0,0" 
        AutomationProperties.AutomationId="ItemGridView" 
        AutomationProperties.Name="Items In Group" 
        ItemTemplate="{StaticResource StandardTripleLineItemTemplate}" 
        SelectionMode="Single" 
        IsSwipeEnabled="false" 
        IsItemClickEnabled="True" 
        ItemClick="ItemView_ItemClickContent"> 
        <ListView.ItemContainerStyle> 

         <Style TargetType="ListViewItem"> 
          <Setter Property="Template"> 
           <Setter.Value> 
            <ControlTemplate TargetType="ListViewItem"> 
             <Grid> 
              <VisualStateManager.VisualStateGroups> 
               <VisualStateGroup x:Name="CommonStates"> 
                <VisualState x:Name="Normal"/> 
               </VisualStateGroup> 
               <VisualStateGroup x:Name="SelectionStates"> 
                <VisualState x:Name="Unselected"> 
                 <Storyboard> 
                  <ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Transparent"/> 
                 </Storyboard> 
                </VisualState> 
                <VisualState x:Name="SelectedUnfocused"> 
                 <Storyboard> 
                  <ColorAnimation Duration="0" Storyboard.TargetName="myback" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="Red"/> 
                 </Storyboard> 
                </VisualState> 
               </VisualStateGroup> 


              </VisualStateManager.VisualStateGroups> 
              <Border x:Name="myback" Background="Transparent"> 
               <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/> 
              </Border> 
             </Grid> 
            </ControlTemplate> 
           </Setter.Value> 
          </Setter> 
         </Style> 
        </ListView.ItemContainerStyle> 
       </ListView> 
      </DataTemplate> 
     </HubSection> 

И мне нужно настроить различные стили ListViewItem различными условиями.

Существует код позади него:

 SampleDataGroup oContentFolder = await MainFunctionality.GetContent(pbActive, m_sUri, sFirstID, m_sSessionID); 

       if (oContentFolder != null) 
       { 
        Section2.Header = sFirstName; 
        this.DefaultViewModel["Section2Items"] = oContentFolder; 

        lv = Utilities.Utilities.FindVisualChildByName<ListView>(Section2, "lvSection2"); 
        if (lv != null) 

         for (int j = 0; j < oContentFolder.Items.Count; j++) 
         { 
          if (oContentFolder.Items[j].ItemType == "ctJob") 
          { 
           if (oContentFolder.Items[j].ItemState == "InWork") 
           { 

          } 

          } 
         } 

         lv.SelectedIndex = 0;  

Как я могу настроить ListViewItem стиль

+0

Я думал, что это должно быть сделано с помощью операций с lv.Items [j], но только класс, к которому может быть преобразован lv.Items [j], является моим SampleDataContent, но не элементом Control или UIFrameworkElement. –

+0

Я бы не поставил его с кодом. Я предпочитаю привязывать свойства к стилизованному элементу с помощью настраиваемого конвертера. – xum59

+0

Я могу добавить некоторые шаблоны к разметке XAML, но как я могу выбрать элемент управления, назначенный текущему элементу ListViewItem для стиля установки. –

ответ

1

Я не эксперт WinRT, но это может помочь:

//The class to style 
public class SampleTaskItem 
    { 
     public SampleTaskItem() 
     { 
      TaskId = (new Random()).Next(); 
     } 
     //Your properties  
     public int TaskId { get; private set; } 

     //Calculate these with your object's data 
     public bool Done { get; set; } 
     public bool Late { get; set; } 
     public bool IsNew { get; set; } 
    } 

    public class TaskItemStyleConverter : IValueConverter 
    { 

     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (value is SampleTaskItem) 
      { 
       var myTask = value as SampleTaskItem; 
       var property = parameter.ToString().ToLower(); 

       if (property == "fontweight") 
       { 
        return myTask.IsNew ? FontWeights.Bold : FontWeights.Normal; 
       } 
       if (property == "foreground") 
       { 
        return myTask.Late ? Brushes.Red : Brushes.Black; 
       } 
       if (property == "strike") 
       { 
        return myTask.Done ? TextDecorations.Strikethrough : null; 
       } 
       throw new NotImplementedException(); 
      } 

      throw new NotImplementedException(); 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

Тогда, ваш ListView может выглядеть примерно так:

<ListView ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type loc:StyledListview}}, Path=SampleTasks}"> 
      <ListView.Resources> 
       <loc:TaskItemStyleConverter x:Key="STYLER"/> 
      </ListView.Resources> 
      <ListView.ItemTemplate> 
       <DataTemplate DataType="{x:Type loc:SampleTaskItem}"> 
        <TextBlock Foreground="{Binding Converter={StaticResource STYLER}, ConverterParameter=foreground}" 
           FontWeight="{Binding Converter={StaticResource STYLER}, ConverterParameter=fontweight}" 
           TextDecorations="{Binding Converter={StaticResource STYLER}, ConverterParameter=strike}" 
           Text="{Binding TaskId}"/> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 

Любой флаг, отмеченный значком SampleTaskItem, вызовет нужный стиль, он может комбинировать ни от одного до другого.

+0

Спасибо. Я попробую. –

+0

xum59, спасибо за ваш ответ. В нотации WinRT может быть какая-то разница, но я понял, что важно преобразовать стиль. Теперь я могу google и msdn в правильном направлении. Спасибо! –

+0

Ответ на xum59 абсолютно прав. Окончательный XAML и код позади: –

Смежные вопросы