dir.by  
  Поиск  
Компьютер, программы
WPF. Windows Presentation Foundation (standalone .exe file)
 Пример портфолио сотрудников с описанием задач: "DataGrid внутри DataGrid используя RowDetailsTemplate" | WPF приложение 
посмотрели 5789 раз
обновлено: 2 October 2022
Нажимаем на Daniel строчку и увидим что открылось описание:
Если нажимаем на Johanes то увидим что открылось описание:
Если нажимаем на Rebeca то увидим что открылось описание:
Шаг 1. Создаем новый проект
Шаг 2. Добавим код в xaml файл
  Файл MainWindow.xaml
<Window x:Class="WpfDataGrids.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:WpfDataGrids"
          mc:Ignorable="d"
          Title="MainWindow" Height="450" Width="800">
     <Grid>

          <!-- data DataGrid -->
          <DataGrid
               AutoGenerateColumns="False"
               Margin="10"
               IsReadOnly="True"
               ItemsSource="{Binding Customers}"
               FontFamily="Gisha" FontSize="20">

               <DataGrid.Columns>
                    <DataGridTextColumn Header="Customer Name" Binding="{Binding CustomerName}" Width="270" />
                    <DataGridTextColumn Header="Country" Binding="{Binding CustomerCountry}" Width="150"/>
                    <DataGridTextColumn Header="Project Name" Binding="{Binding ProjectName}" Width="150"/>
               </DataGrid.Columns>

               <!-- row detail -->
               <DataGrid.RowDetailsTemplate >
                    <DataTemplate>
                         <StackPanel Orientation="Horizontal">

                              <!-- photo -->
                              <Image Source="{Binding CustomerPhoto}" VerticalAlignment="Top"></Image>

                              <!-- tasks -->
                              <TextBlock FontSize="16" FontWeight="Bold">Tasks:</TextBlock>

                              <!-- sub DataGrid -->
                              <DataGrid
                                   AutoGenerateColumns="False"
                                   Margin="10"
                                   IsReadOnly="True"
                                   ItemsSource="{Binding Tasks}"
                                   FontFamily="Gisha" FontSize="20">
                                  
                                   <DataGrid.Columns>
                                        <DataGridTextColumn Header="Task Name" Binding="{Binding TaskName}" Width="150" />
                                        <DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="150"/>
                                        <DataGridTextColumn Header="Estimation (days)" Binding="{Binding Estimation}" Width="150"/>
                                   </DataGrid.Columns>
                                  
                              </DataGrid>

                         </StackPanel>
                    </DataTemplate>
               </DataGrid.RowDetailsTemplate>
          </DataGrid>

     </Grid>
</Window>
Шаг 3. Добавим код в MainWindow.xaml.cs файл
  Файл MainWindow.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;

namespace WpfDataGrids
{
     public class Task
     {
          public string TaskName { get; set; }
          public string Status { get; set; }
          public int Estimation { get; set; }
     }

     public class Customer
     {
          public string CustomerName { get; set; }
          public string CustomerCountry { get; set; }
          public string CustomerPhoto { get; set; }
          public string ProjectName { get; set; }
          public Task[] Tasks { get; set; }
     }

     public partial class MainWindow : Window
     {
          public ObservableCollection<Customer> Customers { get; set; }

          public MainWindow()
          {
               InitializeComponent();

               // for binding
               this.DataContext = this;

               // data for datagrid
               Customers = new ObservableCollection<Customer>()
               {
                         new Customer() {
                              CustomerName="Daniel", CustomerCountry="Germany", CustomerPhoto="D:/Daniel.jpg", ProjectName = "AirLines",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Create login page", Status = "Finished", Estimation = 3 },
                                   new Task(){TaskName = "Update seats page", Status = "In Progrsss", Estimation = 2 },
                                   new Task(){TaskName = "Implement algorithm", Status = "Not Started", Estimation = 4 },
                                   new Task(){TaskName = "Writing tests", Status = "Not Started", Estimation = 3 },
                              } },

                         new Customer() {
                              CustomerName="Johanes", CustomerCountry="USA", CustomerPhoto="D:/Johanes.jpg", ProjectName = "Book shop",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Adding db", Status = "In Progrsss", Estimation = 3 },
                                   new Task(){TaskName = "Query records", Status = "Not Started", Estimation = 3 },
                              } },

                         new Customer() {
                              CustomerName="Rebeca", CustomerCountry="Poland", CustomerPhoto="D:/Rebeca.jpg", ProjectName = "Food site",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Create dishes list", Status = "Finished", Estimation = 5 },
                                   new Task(){TaskName = "Add tests", Status = "In Progrsss", Estimation = 2 },
                                   new Task(){TaskName = "Check resolutions", Status = "Not Started", Estimation = 1 },
                              } }
               };
          }

     }
}
Шаг 4. Сохраним картинки на D: диск
Скачайте эти картинки к себе на компьютер на диск D:/



Скачать пример
WpfDataGrids.zip ...
размер: 60 kb
Если хотим одновременно открывать несколько людей, вот так:
Напишем код в xaml файле:
  Файл MainWindow.xaml
<Window x:Class="WpfDataGrids.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:WpfDataGrids"
          xmlns:l="clr-namespace:WpfDataGrids"
          mc:Ignorable="d"
          Title="MainWindow" Height="450" Width="800">
     <Window.Resources>
          <l:BoolToVisibilityConverter x:Key="boolToVisibility" />
     </Window.Resources>

     <Grid>

          <!-- data DataGrid -->
          <DataGrid
               AutoGenerateColumns="False"
               Margin="10"
               IsReadOnly="True"
               RowDetailsVisibilityMode="Visible"
               ItemsSource="{Binding Customers}"
               SelectedItem="{Binding SelectedCustomer}"
               FontFamily="Gisha" FontSize="20">

               <!-- LeftClick will Expand (by settting flag IsVisible = true) / Collapse (by settting flag IsVisible = false) -->
               <DataGrid.InputBindings>
                    <MouseBinding
 
                        MouseAction="LeftClick"
                         Command="{Binding ClickMouseOnCustomer}"/>
               </DataGrid.InputBindings>

               <DataGrid.Columns>
                    <DataGridTextColumn Header="Customer Name" Binding="{Binding CustomerName}" Width="270" />
                    <DataGridTextColumn Header="Country" Binding="{Binding CustomerCountry}" Width="150"/>
                    <DataGridTextColumn Header="Project Name" Binding="{Binding ProjectName}" Width="150"/>
               </DataGrid.Columns>

               <!-- row detail -->
               <DataGrid.RowDetailsTemplate >
                    <DataTemplate>
                         <StackPanel Orientation="Horizontal"
                              Visibility="{Binding IsVisible, Converter={StaticResource boolToVisibility}}">

                              <!-- photo -->
                              <Image Source="{Binding CustomerPhoto}" VerticalAlignment="Top"></Image>

                              <!-- tasks -->
                              <TextBlock FontSize="16" FontWeight="Bold">Tasks:</TextBlock>

                              <!-- sub DataGrid -->
                              <DataGrid
                                   AutoGenerateColumns="False"
                                   Margin="10"
                                   IsReadOnly="True"
                                   ItemsSource="{Binding Tasks}"
                                   FontFamily="Gisha" FontSize="20">

                                   <DataGrid.Columns>
                                        <DataGridTextColumn Header="Task Name" Binding="{Binding TaskName}" Width="150" />
                                        <DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="150"/>
                                        <DataGridTextColumn Header="Estimation (days)" Binding="{Binding Estimation}" Width="150"/>
                                   </DataGrid.Columns>

                              </DataGrid>

                         </StackPanel>
                    </DataTemplate>
               </DataGrid.RowDetailsTemplate>
          </DataGrid>

     </Grid>
</Window>
Напишем код в MainWindow.xaml.cs файле:
  Файл MainWindow.xaml.cs
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace WpfDataGrids
{
     public class BoolToVisibilityConverter : IValueConverter
     {
          public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
          {
               var bVal = (bool)value;
               return bVal ? Visibility.Visible : Visibility.Collapsed;
          }

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

     public class Task
     {
          public string TaskName { get; set; }
          public string Status { get; set; }
          public int Estimation { get; set; }
     }

     public class Customer : INotifyPropertyChanged
     {
          public string CustomerName { get; set; }
          public string CustomerCountry { get; set; }
          public string CustomerPhoto { get; set; }
          public string ProjectName { get; set; }
          public Task[] Tasks { get; set; }

          private bool _isVisible;
          public bool IsVisible { get => _isVisible; set => Set(ref _isVisible, value); }

          public event PropertyChangedEventHandler PropertyChanged;
          protected void OnPropertyChanged([CallerMemberName] string name = null)
          {
               PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
          }

          protected virtual bool Set<T>(ref T field, T value, [CallerMemberName] string PropertyName = null)
          {
               if (Equals(field, value)) return false;
               field = value;
               OnPropertyChanged(PropertyName);
               return true;
          }
     }

     public class MyClickCommand : ICommand
     {
          public event EventHandler CanExecuteChanged;
          private readonly Action<object> _callback;
          public MyClickCommand(Action<object> callback)
          {
               _callback = callback;
          }

          public virtual void Execute(object parameter)
          {
               _callback(parameter);
          }

          public virtual bool CanExecute(object parameter) { return true; }

     }

     public partial class MainWindow : Window
     {
          private Customer _selectedCustomer;
          public Customer SelectedCustomer
          {
               get
               {
                    return _selectedCustomer;
               }
               set
               {
                    _selectedCustomer = value;
                    if (_selectedCustomer!=null)
                         _selectedCustomer.IsVisible = !_selectedCustomer.IsVisible;
               }
          }

          public ObservableCollection<Customer> Customers { get; set; }
          // button handler
          public ICommand ClickMouseOnCustomer { get; }

          public MainWindow()
          {
               InitializeComponent();

               // for binding
               this.DataContext = this;

               ClickMouseOnCustomer = new MyClickCommand((param) => {
                    var customer = _selectedCustomer;
                    if (customer != null)
                    {
                         customer.IsVisible =!customer.IsVisible;
                    }
               });

               // data for grid
               Customers = new ObservableCollection<Customer>()
               {
                         new Customer() {
                              CustomerName="Daniel", CustomerCountry="Germany", CustomerPhoto="D:/Daniel.jpg", ProjectName = "AirLines",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Create login page", Status = "Finished", Estimation = 3 },
                                   new Task(){TaskName = "Update seats page", Status = "In Progrsss", Estimation = 2 },
                                   new Task(){TaskName = "Implement algorithm", Status = "Not Started", Estimation = 4 },
                                   new Task(){TaskName = "Writing tests", Status = "Not Started", Estimation = 3 },
                              } },

                         new Customer() {
                              CustomerName="Johanes", CustomerCountry="USA", CustomerPhoto="D:/Johanes.jpg", ProjectName = "Book shop",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Adding db", Status = "In Progrsss", Estimation = 3 },
                                   new Task(){TaskName = "Query records", Status = "Not Started", Estimation = 3 },
                              } },

                         new Customer() {
                              CustomerName="Rebeca", CustomerCountry="Poland", CustomerPhoto="D:/Rebeca.jpg", ProjectName = "Food site",
                              Tasks = new Task[] {
                                   new Task(){TaskName = "Create dishes list", Status = "Finished", Estimation = 5 },
                                   new Task(){TaskName = "Add tests", Status = "In Progrsss", Estimation = 2 },
                                   new Task(){TaskName = "Check resolutions", Status = "Not Started", Estimation = 1 },
                              } }
               };
          }

     }
}
Скачать пример
WpfDataGrids2.zip ...
размер: 60 kb
 
← Previous topic
Example "DataGrid: sorting the column according to our own algorithm (Custom Sort)" | WPF application
 
Next topic →
Example "In the ListView, expand the column when adding data (auto column width)" | WPF application
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
WPF Simple New Application
Creating a New WPF Application | C#
WPF layout
Making a layout with DockPanel and StackPanel in WPF
Events
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you left-click on Grid and draw a line"| C# WPF application
Example "When you double-click on Grid, we show the message"| C# WPF application
WPF elements
Label
Example "Setting the text in Label" via c# code | WPF application
FontAwesome icons
Example "I show icons, for the icon I connect the fontawesome5" library | C# WPF application
Example "I make animations for icons, library fontawesome5" | C# WPF application
 <BR>
TextBlock
Example "Set the text in the TextBlock using Binding". Let"s also add double Bindning using INotifyPropertyChanged | C# WPF application
Example "Several TextBlocks (showing the texts) and making the element where mouse (mouse over)" | C# WPF application
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Button
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
TextBox
Example "Installing and getting text in a TextBox using Binding" | C# WPF application
Example "Set text in TextBox" via c# code | WPF application
 <BR>
TextBox with Place Holder
Example "Showing the Place Holder in TextBox" | WPF application
Example "Showing a Place Holder with an icon in TextBox", for the icon I include the fontawesome5 library | WPF application
 <BR>
TextBox with text validation
Example "Set the text in the TextBox using Binding and do validation (if the text is not correct)" | C# WPF application
 <BR>
ComboBox
Example "In ComboBox, we do text editing. Getting the text using Binding" | C# WPF application
 <BR>
ItemsControl
Example "ItemsControl, button and click handler" | WPF application
Grid
What is Grid in WPF
How to Add RowDefinition, ColumnDefinition to a Grid (with the mouse in the XAML design editor) | C# WPF application
Adding vertical scrolling | WPF application
DataGrid
Example "DataGrid doing bind data", button and click handler in DataGrid, text alignment in DataGrid, scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
How do I color row when I click on row (change background for selected row) in DataGrid? | C# WPF application
How do I highlight a row DataGrid (make background) ? | C# WPF application
Example "DataGrid: sorting the column according to our own algorithm (Custom Sort)" | WPF application
DataGrid inside DataGrid
Example of an employee portfolio with task descriptions: "DataGrid inside DataGrid using RowDetailsTemplate" | WPF application
 <BR>
ListView
Example "In the ListView, expand the column when adding data (auto column width)" | WPF application
Example "In the ListView, we use ItemTemplate DataTemplate" | WPF application
 <BR>
ScrollViewer
Adding vertical scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
Example "Do ScrollBar less(more) in ScrollViewer" | C# WPF application
Resource file
Add an image (jpg, bmp, png) to the project and mark it as Resource | C# WPF application
Image
In the Image element, show the image (jpg, bmp, png) from Resource | C# WPF application
Select the image (jpg, bmp, png) from the computer and show it in the Image element. Saving the image to the database | C# WPF application
Example "In the Image element, make a Binding for Source" | C# WPF application
Example "Convert the base64 text to a Bitmap image and show it in the Image element" | C# WPF application
Example "Open an SVG file and show the image in the Image element" | C# WPF application
 <BR>
Canvas
Example "Create a Canvas and draw a picture" C# WPF
Example "Drawing a picture with movement on Canvas" C# WPF
Example "Drawing a picture with motion and sprite animation on Canvas" C# WPF
 <BR>
Line
How to Draw a Line | C# WPF application
Example "Create and draw a line by left-clicking on Grid"| Grid Line | C# WPF application
Convert the image to XAML Path Geometry
Convert SVG to XAML (using Adobe Illustrator), populate the Path Data Geometry, show the lines on the screen | C# WPF application
Convert SVG to XAML (using Dias SVG to UWP XAML Converter), populate the Path Data Geometry, show the lines on the screen | C# WPF application
How to Convert PNG to SVG to XAML | C# WPF application
Converter SVG to XAML | WPF C#
How to Convert XAML to SVG | C# WPF application
ViewBox
Example "ViewBox Binding for Left, Top, Width, Height, ContetnPresenter binding" | C# WPF application
Width by percentage
Divide the screen vertically (by width) into 2 equal parts of the screen (width1 = 50%, width2 = 50%), use Grid | C# WPF application
Split the screen vertically (by width) into 2 parts (width1 = 70%, width2 = 30%), using Grid | C# WPF application
Example "Set the width of the element as a percentage of the width of the parent element" (width in percentage), write your IValueConverter | C# WPF application
Database (Entity Framework)
Entity Framework in a WPF application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Creating Your WPF Elements
Example "Create your own WPF element using Style and a new xaml file. The new element is: at the top Title, at the bottom the text in the frame. Using Binding | C# WPF application
Example "Create your new WPF element with your own properties in the new cs and xaml files. In WPF, a new element: Title at the top, text at the bottom, and in the box | C# WPF application
WPF application with Prism library (MVVM design pattern)
Create a new WPF application with Prism Unity (splitting the project into Services, Views, ViewModels folders). MVVM (Model-View-ViewModel) Patern | C#
WPF application with Prism Unity. In the Tab app and splitting into separate xamls using Region.
WPF application with Locator (MVVM design pattern)
Creating a new WPF application with Locator (dividing the project into Views, ViewModels folders)
How do I add Dependency Injection, boot from appsettings.json in a new WPF application?
Automated Tests
Writing an automated test for a WPF C# application (using Nuget.Appium and the AutomationProperties.AutomationId property)
Interview Questions
What is the difference between static resource and dynamic resource? | WPF C#
Additional topics, questions
Open the properties window for a graphic element in WPF application C#
Errors
Error "To run this application, you must install .NET. Would you like to download it now?" | I run WPF the application on C#
Books
WPF Study Books

  Ваши вопросы присылайте по почте: info@dir.by