简体   繁体   English

如何将列表绑定到 wpf 中的数据网格列

[英]How to bind a list to datagrid columns in wpf

I have a class containting 7 list strings(sun, mon, tue...).我有一个包含 7 个列表字符串(sun、mon、tue...)的类。 In my class, I am populating these list strings with the days in a month.在我的课堂上,我用一个月中的天数填充这些列表字符串。 I then create another list and added the result to it.然后我创建另一个列表并将结果添加到其中。 For example, if we take January 2019, sun will have the values, 6, 13, 20 and 27. I then make my grids itemsource to be this list but then my grid is blank.例如,如果我们取 2019 年 1 月,sun 的值将是 6、13、20 和 27。然后我将我的网格 itemsource 设为这个列表,但我的网格是空白的。 Below is my code, what am I missing or doing wrong?下面是我的代码,我错过了什么或做错了什么?

model模型

    public class MonthModel
   {
    //public string sun { get; set; }
    public List<string> sun = new List<string>();     
    public List<string> mon = new List<string>();
    public List<string> tue = new List<string>();
    public List<string> wed = new List<string>();
    public List<string> thu = new List<string>();
    public List<string> fri = new List<string>();
    public List<string> sat = new List<string>();

}

class班级

         switch (cTvDaySelected)
        {

                case "January":
                int Year = DateTime.Today.Year;
                int Month = 1;                 
                int TotalDaysInMonth = DateTime.DaysInMonth(Year, Month);

                    for (int i = 1; i <= TotalDaysInMonth; i++)
                    {
                        DateTime dt = new DateTime(Year, Month, i);
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "sun")
                        {
                            dm.sun.Add(dt.ToShortDateString().Substring(0, 2));                 
                            //dm.sun = dt.ToShortDateString().Substring(0, 2);
                        }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "mon")
                        {
                        // dm.mon = dt.ToShortDateString().Substring(0, 2);
                          dm.mon.Add(dt.ToShortDateString().Substring(0, 2));
                    }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "tue")
                        {
                        // dm.tue = dt.ToShortDateString().Substring(0, 2);
                        dm.tue.Add(dt.ToShortDateString().Substring(0, 2));
                    }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "wed")
                        {
                        //dm.wed = dt.ToShortDateString().Substring(0, 2);
                        dm.wed.Add(dt.ToShortDateString().Substring(0, 2));
                    }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "thu")
                        {
                        //dm.thu = dt.ToShortDateString().Substring(0, 2);
                        dm.thu.Add(dt.ToShortDateString().Substring(0, 2));
                    }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "fri")
                        {
                        //dm.fri = dt.ToShortDateString().Substring(0, 2);
                        dm.fri.Add(dt.ToShortDateString().Substring(0, 2));
                    }
                        if (dt.DayOfWeek.ToString().ToLower().Substring(0, 3) == "sat")
                        {
                        // dm.sat = dt.ToShortDateString().Substring(0, 2);
                          dm.sat.Add(dt.ToShortDateString().Substring(0, 2));
                    }

                    }
                    Month_Model.Add(dm);

               // month_record.Items.Add(dm);

                month_record.ItemsSource = Month_Model;
                 break;
        }

xaml xml

   <DataGrid x:Name="month_record"  MouseDoubleClick="Month_record_MouseDoubleClick" 
     IsReadOnly="True" Grid.ColumnSpan="9" Grid.Column="1" SelectionMode="Extended" 
   SelectionUnit="Cell" VerticalGridLinesBrush="Silver" HorizontalGridLinesBrush="Silver" 
   AutoGenerateColumns="False" ScrollViewer.VerticalScrollBarVisibility="Visible" 
   ScrollViewer.HorizontalScrollBarVisibility="Visible" Visibility="Hidden" Grid.Row="4" >
   <DataGrid.Columns>
  <DataGridTextColumn Binding="{Binding sun}" IsReadOnly="True" x:Name="colMSun" Header="Sunday" 
  Width="Auto">
  <DataGridTextColumn.ElementStyle>
    <Style TargetType="{x:Type TextBlock}">
    <Style.Triggers>
    <Trigger Property="Text" Value="B">
    <Setter Property="Background" Value="#C1D5F8"/>
    </Trigger>
    </Style.Triggers>
     </Style>
    </DataGridTextColumn.ElementStyle>
     </DataGridTextColumn>
    <DataGridTextColumn Binding="{Binding Path=mon}" x:Name="colMMon" 
   IsReadOnly="True" Header="Monday" Width="Auto">
   <DataGridTextColumn.ElementStyle>
   <Style TargetType="{x:Type TextBlock}">
     <Style.Triggers>
     <Trigger Property="Text" Value="B">
     <Setter Property="Background" Value="#C1D5F8"/>
      </Trigger>
      </Style.Triggers>
     </Style>
    </DataGridTextColumn.ElementStyle>
     </DataGridTextColumn>
      <DataGridTextColumn Binding="{Binding Path=tue}" x:Name="colMTue" 
       IsReadOnly="True" Header="Tuesday" Width="Auto">
       <DataGridTextColumn.ElementStyle>
       <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
        <Trigger Property="Text" Value="B">
         <Setter Property="Background" Value="#C1D5F8"/>
         </Trigger>
         </Style.Triggers>
          </Style>
          </DataGridTextColumn.ElementStyle>
           </DataGridTextColumn>
           <DataGridTextColumn Binding="{Binding Path=wed}" IsReadOnly="True" 
            x:Name="colMWed" Header="Wednesday" Width="Auto">
            <DataGridTextColumn.ElementStyle>
             <Style TargetType="{x:Type TextBlock}">
              <Style.Triggers>
               <Trigger Property="Text" Value="B">
                <Setter Property="Background" Value="#C1D5F8"/>
                </Trigger>
                  </Style.Triggers>
                  </Style>
                  </DataGridTextColumn.ElementStyle>
                  </DataGridTextColumn>
                  <DataGridTextColumn Binding="{Binding Path=thu}" IsReadOnly="True" 
                   x:Name="colMThu" Header="Thursday" Width="Auto">
                   <DataGridTextColumn.ElementStyle>
                     <Style TargetType="{x:Type TextBlock}">
                    <Style.Triggers>
                    <Trigger Property="Text" Value="B">
                    <Setter Property="Background" Value="#C1D5F8"/>
                    </Trigger>
                      </Style.Triggers>
                       </Style>
                       </DataGridTextColumn.ElementStyle>
                      </DataGridTextColumn>
                      <DataGridTextColumn Binding="{Binding Path=fri}" x:Name="colMFri" 
                      IsReadOnly="True" Header="Friday" Width="Auto">
                      <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                         <Style.Triggers>
                          <Trigger Property="Text" Value="B">
                            <Setter Property="Background" Value="#C1D5F8"/>
                              </Trigger>
                                </Style.Triggers>
                               </Style>
                         </DataGridTextColumn.ElementStyle>
                          </DataGridTextColumn>
                          <DataGridTextColumn Binding="{Binding Path=sat}" x:Name="colMSat" 
                           IsReadOnly="True" Header="Saturday" Width="Auto">
                            <DataGridTextColumn.ElementStyle>
                            <Style TargetType="{x:Type TextBlock}">
                              <Style.Triggers>
                               <Trigger Property="Text" Value="B">
                                 <Setter Property="Background" Value="#C1D5F8"/>
                                  </Trigger>
                                  </Style.Triggers>
                               </Style>
                              </DataGridTextColumn.ElementStyle>
                         </DataGridTextColumn>
                        </DataGrid.Columns>                              
                     </DataGrid>

There are couple of issues with your code.您的代码有几个问题。

  1. You have made your data grid Visibility to "Hidden".您已将数据网格可见性设置为“隐藏”。 So you are not able to see anything in your window.因此,您无法在窗口中看到任何内容。

  2. You are trying to bind a collection to a TextBlock.您正在尝试将集合绑定到 TextBlock。 This is the your question too.这也是你的问题。

You cannot bind a collection to a TextBlock.不能将集合绑定到 TextBlock。 If you wanted to achieve this then you can have a ComboBox in your DataGrid cell and bind the list to it.如果您想实现这一点,那么您可以在 DataGrid 单元格中有一个 ComboBox 并将列表绑定到它。

Or else要不然

You can follow below steps where I have made a concatenation of each property as a comma separated string.您可以按照以下步骤操作,其中我将每个属性连接为逗号分隔的字符串。

  1. Your class members are fields and not properties.您的类成员是字段而不是属性。 I am not sure if this also a problem but the moment I have changed them to properties, I can able to see something coming up in Columns.我不确定这是否也是一个问题,但是当我将它们更改为属性时,我可以在列中看到一些内容。

So I have made changes following,所以我做了以下更改,

  1. Changed class level public fields to properties - You can ignore this because the actual data I am binding to DataGridTextColumn is "Sunday" (a property) of my MonthModel class.将类级别的公共字段更改为属性 - 您可以忽略这一点,因为我绑定到 DataGridTextColumn 的实际数据是我的 MonthModel 类的“Sunday”(一个属性)。 So doing this is not very mandatory but your "Sunday" should be a property.所以这样做不是强制性的,但你的“星期日”应该是一个属性。

See below for the updated class.请参阅下面的更新类。

    public class MonthModel
    {
        public List<string> sun { get; set; } = new List<string>();
        public List<string> mon { get; set; } = new List<string>();
        public List<string> tue { get; set; } = new List<string>();
        public List<string> wed { get; set; } = new List<string>();
        public List<string> thu { get; set; } = new List<string>();
        public List<string> fri { get; set; } = new List<string>();
        public List<string> sat { get; set; } = new List<string>();


        public string Sunday
        {
            get
            {
                return string.Join(",", sun);
            }
        }
    }

Note:- I have created only a single property "Sunday" and concatenating the list as a "," (comma) separated string.注意:-我只创建了一个属性“Sunday”并将列表连接为“,”(逗号)分隔的字符串。

You can create similar way for other properties or change it according to your needs.您可以为其他属性创建类似的方式或根据您的需要更改它。

Approach 1 -方法 1 -

  1. Visibility of DataGrid made to Visible (hope you missed this at first point) and I am now binding "Sunday" property to DataGridTextColumn DataGrid 的可见性变为 Visible(希望你一开始就错过了这一点),我现在将“Sunday”属性绑定到 DataGridTextColumn

     <DataGrid x:Name="month_record" MouseDoubleClick="month_record_MouseDoubleClick" IsReadOnly="True" Grid.ColumnSpan="9" Grid.Column="1" SelectionMode="Extended" SelectionUnit="Cell" VerticalGridLinesBrush="Silver" HorizontalGridLinesBrush="Silver" AutoGenerateColumns="False" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible" Visibility="Visible" Grid.Row="4"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Sunday}" IsReadOnly="True" x:Name="colMSun" Header="Sunday" Width="Auto"> <DataGridTextColumn.ElementStyle> <Style TargetType="{x:Type TextBlock}"> <Style.Triggers> <Trigger Property="Text" Value="Sunday"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> </DataGridTextColumn.ElementStyle> </DataGridTextColumn> </DataGrid.Columns> </DataGrid> }

Note:- I am not pasting all columns here, but you have to do it on yourself.注意:-我不会在这里粘贴所有列,但您必须自己完成。 I hope you can able to make changes with above changes.我希望您能够通过上述更改进行更改。

I haven't made any changes to code-behind of your methods.我没有对您的方法的代码隐藏进行任何更改。

Approach 2 -方法 2 -

If you are okay to have a combobox in your datagrid column then see below small code snippet,如果您可以在数据网格列中有一个组合框,请参阅下面的小代码片段,

              <DataGridTemplateColumn Header="Combobox">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox SelectedIndex="0" ItemsSource="{Binding sun}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

Hope any of the above approaches might helps you.希望以上任何一种方法都可以帮助您。 If not then let us know your alternative ideas on how you wanted to represent UI so that we can have a better ideas.如果没有,那么请让我们知道您关于如何表示 UI 的替代想法,以便我们可以有更好的想法。

Suggestions:-建议:-

And small suggestions from my end after looking at your code查看您的代码后,我的小建议

Use observable collection and bind as an source to your DataGrid.使用 observable 集合并将其作为源绑定到您的 DataGrid。

Implement INotifyPropertyChanged to listen for the value changes and refresh UI automatically.实现 INotifyPropertyChanged 以侦听值更改并自动刷新 UI。

Improve your naming conventions that you give to your class, properties, objects.改进您为类、属性、对象提供的命名约定。

Hope this helps.希望这可以帮助。 Please give a try and let us know in case if any issues exists.请尝试一下,如果存在任何问题,请告诉我们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM