Rabee3-F1.787545 Ответов: 1

Элементы Datagrid в WPF


<DataGrid x:Name="GrdSubject" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MaxWidth="600" Background="{x:Null}" Margin="10,130,10,10" SelectionChanged="GrdSubject_SelectionChanged">
            <DataGrid.BorderBrush>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="#FFFFF2F2" Offset="1"/>
                </LinearGradientBrush>
            </DataGrid.BorderBrush>

            <DataGrid.Columns>
                <DataGridTextColumn x:Name="ClId"   Header="ID"  Width="100" Visibility="Visible" Binding="{Binding SubId}"/>
                <DataGridTextColumn x:Name="ClSubject" Header="Subject"  Width="250"  Binding="{Binding SubName}"/>
                <DataGridTextColumn x:Name="ClStatus" Header="Status"  Width="100"  Binding="{Binding SubStatus}"/>

            </DataGrid.Columns>

        </DataGrid>



public class Subject
   {
       public int SubId { set; get; }
       public string SubName { set; get; }
       public string SubStatus { set; get; }
   }


Что я уже пробовал:

string id = "";
string sub=";
            var sub = new Subject();
            if (GrdSubject.SelectedItem!=null)
            {
                sub = GrdSubject.SelectedItem as Subject;
                if (sub!=null)
                {
                    id = sub.SubId.ToString();
                    MessageBox.Show(id.Length.ToString()); //just to check the word results always 200 but in real is 2 or 3 
                    MessageBox.Show(sub.SubName.Length.ToString()); //just to check the word results always 200 but in real is 5 or 6 
 and this is the problem "id                      " many spaces after the word to reach 200 as length
                    
                    
                }
            }

1 Ответов

Рейтинг:
11

Graeme_Grant

Ваш вопрос не содержит подробностей, а ваш код неполон, поэтому я догадываюсь, что вы пытаетесь сделать.

Я предпочитаю работать с шаблоном проектирования MVVM, но вот решение, использующее жестко связанный код позади.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LoadData();
    }

    private ObservableCollection<Subject> Subjects { get; } = new ObservableCollection<Subject>();
    private void LoadData()
    {
        for (int i = 0; i < 10; i++)
        {
            Subjects.Add(new Subject
            {
                SubId = i,
                SubName = "Name " + i,
                SubStatus = "Status " + (10 - i)
            });
        }

        SubjectDataGrid.ItemsSource = Subjects;

    }

    private void SubjectDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (SubjectDataGrid.SelectedItem != null)
        {
            var item = SubjectDataGrid.SelectedItem as Subject;
            Id.Text = item.SubId.ToString();
            Name.Text = item.SubName;
            Status.Text = item.SubStatus;
        }
        else
        {
            Id.Text = "";
            Name.Text = "";
            Status.Text = "";
        }
    }
}

А вот и вид из окна:
<Window x:Class="DataGridSelectedItemCodeBehind.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:DataGridSelectedItemCodeBehind"

        mc:Ignorable="d"

        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <DataGrid Name="SubjectDataGrid"

                  SelectionChanged="SubjectDataGrid_OnSelectionChanged"/>
        <Grid Column="1" VerticalAlignment="Center" Margin="20">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.Resources>
                <Style TargetType="StackPanel">
                    <Setter Property="Orientation" Value="Horizontal"/>
                </Style>
                <Style TargetType="Label">
                    <Setter Property="Margin" Value="10"/>
                    <Setter Property="Width" Value="50"/>
                </Style>
                <Style TargetType="Border">
                    <Setter Property="Padding" Value="2"/>
                    <Setter Property="Margin" Value="0 4"/>
                    <Setter Property="Width" Value="200"/>
                    <Setter Property="BorderBrush" Value="Silver"/>
                    <Setter Property="BorderThickness" Value="2"/>
                </Style>
                <Style TargetType="TextBlock">
                    <Setter Property="VerticalAlignment" Value="Center"/>
                </Style>
            </Grid.Resources>
            <StackPanel>
                <Label Content="ID:"/>
                <Border>
                    <TextBlock Name="Id"/>
                </Border>
            </StackPanel>
            <StackPanel Grid.Row="1">
                <Label Content="Name:"/>
                <Border>
                    <TextBlock Name="Name"/>
                </Border>
            </StackPanel>
            <StackPanel Grid.Row="2">
                <Label Content="Status:"/>
                <Border>
                    <TextBlock Name="Status"/>
                </Border>
            </StackPanel>
        </Grid>
    </Grid>
</Window>