WPF datagrid DataGridTemplateColumn set width and when selected background changed

<Window x:Class="WpfApp23.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:WpfApp23"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <SolidColorBrush x:Key="redColor"
                         Color="Red"/>
        <SolidColorBrush x:Key="blueColor"
                         Color="Blue"/>
    </Window.Resources>
    <Grid>
        <DataGrid AutoGenerateColumns="False"
                  ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">            
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Setter Property="BorderThickness" Value="1"/>
                            <Setter Property="Background" Value="{DynamicResource blueColor}"/>
                            <Setter Property="Height" Value="100"/>
                            <Setter Property="Width" Value="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
                            <Setter Property="FontSize" Value="30"/>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="FontSize" Value="50"/>
                                    <Setter Property="Background" Value="{DynamicResource redColor}"/>
                                    <Setter Property="Height" Value="300"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                                    <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                                    <TextBlock Text="{Binding Title}" Grid.Row="1" Grid.Column="0"/>
                                    <TextBlock Text="{Binding ISBN}" Grid.Row="1" Grid.Column="1"/>
                                </Grid>                               
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

 

 

 

 

 

 

 

//xaml
<Window x:Class="WpfApp23.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:WpfApp23"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <SolidColorBrush x:Key="redColor"
                         Color="Red"/>
    </Window.Resources>
    <Grid>
        <DataGrid AutoGenerateColumns="False"
                  ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">            
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Setter Property="BorderThickness" Value="1"/>
                            <Setter Property="Background" Value="{Binding ImgBrush}"/>
                            <Setter Property="Height" Value="100"/>
                            <Setter Property="Width" Value="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
                            <Setter Property="FontSize" Value="30"/>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="FontSize" Value="50"/>
                                    <Setter Property="Background" Value="{DynamicResource redColor}"/>
                                    <Setter Property="Height" Value="300"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                                    <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                                    <TextBlock Text="{Binding Title}" Grid.Row="1" Grid.Column="0"/>
                                    <TextBlock Text="{Binding ISBN}" Grid.Row="1" Grid.Column="1"/>
                                </Grid>                               
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp23
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM();
            this.DataContext = vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            InitBooksList();
        }

        private void InitBooksList()
        {
            var imgsDir = @"../../../Images";
            if(Directory.Exists(imgsDir))
            {
                var imgs=Directory.GetFiles(imgsDir);
                int imgsCount = imgs.Count();
                BooksList = new ObservableCollection<Book>();
                for (int i = 0; i < 100; i++)
                {
                    BooksList.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        Title = $"Title_{i + 1}",
                        ISBN = $"ISBN_{i + 1}",
                        ImgBrush=new ImageBrush(GetImgSourceViaUrl(imgs[i % imgsCount]))
                    });
                }
            }
        }

        private ImageSource GetImgSourceViaUrl(string imgUrl)
        {
            if(!File.Exists(imgUrl))
            {
                return null;
            }
            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri(imgUrl, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            return bmi;
        }

        private Book selectedBk;
        public Book SelectedBk
        {
            get
            {
                return selectedBk;
            }
            set
            {
                if(value!= selectedBk)
                {
                    selectedBk = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<Book> booksList;
        public ObservableCollection<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                if (value != booksList)
                {
                    booksList = value;
                    OnPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string ISBN { get; set; }
        public ImageBrush ImgBrush { get; set; }
    }
}

 

posted @ 2025-05-23 15:11  FredGrit  阅读(14)  评论(0)    收藏  举报