Моделирование WPF DataGrid

Пожалуйста, взгляните на этот стек-блиц-угловая форма-группа-массив . Упрощенный пример formArray.

Так что в моем примере это будет:

form: FormGroup = this.fb.group({
  tops: this.fb.array([])
}, {
  validator: this.exampleValidator
});

exampleValidator(e) {
  //does logic for validity on form
  console.log(e);
}
export class SelectMultipleExample implements OnInit {


  form: FormGroup = this.fb.group({
    tops: this.fb.array([])
  });

  toppingList = [{
      id: 0,
      name: 'Extra cheese'
    },
    {
      id: 0,
      name: 'Mushroom'
    },
    {
      id: 0,
      name: 'Onion'
    },
    {
      id: 0,
      name: 'Pepperoni'
    },
    {
      id: 0,
      name: 'Sausage'
    },
    {
      id: 0,
      name: 'Tomato'
    }
  ];

  complexOrderToppings = [{
      order: {
        selected: [{
            id: 0,
            name: "Extra cheese"
          },
          {
            id: 0,
            name: "Mushroom"
          },
          {
            id: 0,
            name: "Onion"
          },
          {
            id: 0,
            name: "Pepperoni"
          }
        ]
      }
    },
    {
      order: {
        selected: [{
            id: 0,
            name: "Extra cheese"
          },
          {
            id: 0,
            name: "Mushroom"
          },
          {
            id: 0,
            name: "Onion"
          },
          {
            id: 0,
            name: "Pepperoni"
          }
        ]
      }
    },
    {
      order: {
        selected: [{
            id: 0,
            name: "Extra cheese"
          },
          {
            id: 0,
            name: "Mushroom"
          },
          {
            id: 0,
            name: "Onion"
          },
          {
            id: 0,
            name: "Pepperoni"
          }
        ]
      }
    }
  ];

  simpleOrderToppings = [{
      order: [{
          id: 0,
          name: "Extra cheese"
        },
        {
          id: 0,
          name: "Mushroom"
        },
        {
          id: 0,
          name: "Onion"
        },
        {
          id: 0,
          name: "Pepperoni"
        }
      ]
    },
    {
      order: [{
          id: 0,
          name: "Extra cheese"
        },
        {
          id: 0,
          name: "Mushroom"
        },
        {
          id: 0,
          name: "Onion"
        },
        {
          id: 0,
          name: "Pepperoni"
        }
      ]
    },
    {
      order: [{
          id: 0,
          name: "Extra cheese"
        },
        {
          id: 0,
          name: "Mushroom"
        },
        {
          id: 0,
          name: "Onion"
        },
        {
          id: 0,
          name: "Pepperoni"
        }
      ]
    }
  ];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.setToppings(this.complexOrderToppings);
  }

  get getTops(): FormArray {
    return this.form.get('tops') as FormArray;
  }

  setToppings(toppings: any) {
    const toppingsFGs = toppings.map(topping => this.fb.group(topping));
    const topppingFormArray = this.fb.array(toppingsFGs);
    this.form.setControl('tops', topppingFormArray);
    this.setTopsNewValue();
  }

  compareSelected(o1: any, o2: any): boolean {
    if (!o1 || !o2) {
      return false;
    }
    const isSelected = o1.name === o2.name && o1.id === o2.id;
    return isSelected;
  }

  setTopsNewValue() {
    const tops = this.getTops;
    tops.controls.map(t => {
      const newValue = t.value.order.selected;
      t.setValue({
        order: newValue
      });
    });
  }
}


/**  Copyright 2018 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */
{{topping.name}}
{{form.value | json}}

5
задан Dave Clemmer 25 August 2011 в 15:18
поделиться

3 ответа

Результат похож на это. сопроводительный текст http://iwebthereforeiam.com/files/ScreenShot.gif

Вот код, который должен продемонстрировать идею.

XAML:

<Window x:Class="StackOverflow_545979.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:StackOverflow_545979"
    xmlns:debug="clr-namespace:System.Diagnostics;assembly=System"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <local:GreekGods  x:Key="GreekGods"/>
        <DataTemplate x:Key="itemTemplate">
            <Border BorderBrush="RoyalBlue" BorderThickness="2" Margin="2" Padding="5">
                <WrapPanel Orientation="Vertical">
                    <TextBlock Width="200" Text="{Binding Path=Name}"/>
                    <TextBlock Width="200" Text="{Binding Path=Description}"/>
                    <TextBlock Width="200" Text="{Binding Path=RomanName}"/>
                </WrapPanel>
            </Border>
        </DataTemplate>
    </Window.Resources>

    <ListBox ItemTemplate="{StaticResource itemTemplate}" 
             ItemsSource="{StaticResource GreekGods}" />
</Window>

Код C#:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace StackOverflow_545979
{
    public class GreekGod
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string RomanName { get; set; }

        public GreekGod() { }
        public GreekGod(string name, string description, string romanName)
        {
            this.Name = name;
            this.Description = description;
            this.RomanName = romanName;
        }
    }

    public class GreekGods : ObservableCollection<GreekGod>
    {
        public GreekGods()
        {
            this.Add(new GreekGod("Aphrodite", "Goddess of love, beauty and fertility", "Venus"));
            this.Add(new GreekGod("Apollo", "God of prophesy, music and healing", "Apollo"));
            this.Add(new GreekGod("Ares", "God of war", "Mars"));
            this.Add(new GreekGod("Artemis", "Virgin goddess of the hunt", "Diana"));
            this.Add(new GreekGod("Athena", "Goddess of crafts and the domestic arts", "Athena"));
            this.Add(new GreekGod("Demeter", "Goddess of agriculture", "Ceres"));
            this.Add(new GreekGod("Dionysus", "God of wine", "Bacchus"));
            this.Add(new GreekGod("Hephaestus", "God of fire and crafts", "Vulcan"));
            this.Add(new GreekGod("Hera", "Goddess of marriage", "Juno"));
            this.Add(new GreekGod("Hermes", "Messenger of the Gods", "Mercury"));
            this.Add(new GreekGod("Poseidon", "God of the sea, earthquakes and horses", "Neptune"));
            this.Add(new GreekGod("Zeus", "Supreme God of the Olympians", "Jupiter"));
        }
    }
}

GreekGod и классы GreekGods сняты с примеров Bea Stollnitz.

5
ответ дан 14 December 2019 в 09:01
поделиться

Вместо datagrid попытайтесь использовать комбинацию listview или поля списка (в зависимости от которой функциональности Вы хотите - оба происходят из ItemsSource), и datatemplates. Оба из них являются стандартным WPF, не частью инструментария.

http://blah.winsmarts.com/2007-3-WPF__The_DataTemplate,_choosing_how_your_data_will_look_like.aspx

1
ответ дан 14 December 2019 в 09:01
поделиться

Я не знаю, как сделать это с DataGrid Инструментария WPF, и я сомневаюсь, что это - то, в чем Вы на самом деле нуждаетесь. Можно сделать это с ListView или ListBox. Установите ListView. Представление к WrapPanel с IsItemsSource = "Верный". Затем используйте DataTemplate для создания карт. Существует довольно хороший пример, который получит Вас большая часть пути там здесь.

1
ответ дан 14 December 2019 в 09:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: