组合框绑定到ObservableCollection

时间:2018-07-12 13:07:19

标签: c# wpf xaml data-binding observablecollection

我从using HtmlAgilityPack; namespace ConsoleApp1 { class Program { static void Main(string[] args) { HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load("https://www.videoblocks.com/video/after-effects-cs5-template-bracket-titles-65zdx8e"); var title = doc.DocumentNode.SelectNodes(xpath: "//ul[@class='stockItemInfo-stockSpec']").FirstOrDefault().InnerText.Split(':').FirstOrDefault(); var secp = doc.DocumentNode.SelectNodes("//ul[@class='stockItemInfo-stockSpec']//li//span").FirstOrDefault().InnerText; Console.Write(title+":"+secp); Console.ReadKey(); } } } 中填充了DataGrid,并且绑定了ObservableCollection,但是相同的解决方案不适用于Buttons。我已经尝试了一些修复程序,但是每次ComboBox里面都是空的。

XAML:

ComboBox

绑定代码:

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
    <DataGridTemplateColumn Header="Monday" Width="auto">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <StackPanel>

                    <ComboBox x:Name="comboBoxShift" Margin="10,0,0,0" DisplayMemberPath="{Binding Path=Shifts_value}" SelectedValuePath="{Binding Path=Shifts_id}" SelectedValue="{Binding Path=Shifts_selected}" VerticalAlignment="Top" Height="25" Width="auto" FontSize="10" DropDownClosed="comboBoxShift_DropDownClosed">             
                    </ComboBox>

                    <Button Name="ButtonStandby" Margin="10 0 0 0"  Content="Standby" Height="25" Width="auto" IsEnabled="True" FontSize="10" FontWeight="UltraBold" Background="{Binding Path=day1_f_standby}">
                    </Button>
                </StackPanel>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

ObservableCollection代码:

public class CalendarGlobals
{
     public static ObservableCollection<Person> currentTeamOC { get; set; }
}   

    public TeamScheduleWindow()
{ 
     InitializeComponent();
     dataGrid.ItemsSource = CalendarGlobals.currentTeamOC; 
}

我删除了不相关的代码,以使这篇文章简短。 预先感谢您的帮助。

编辑: 感谢@MKloster的帮助

我成功使用了您的解决方案,但是我在ObservableCollection代码中添加了新对象

public class Person
{
    public int day1_id_ca { get; set; }
    public int day1_f_shift { get; set; }
    public string day1_f_wfh { get; set; }
    public string day1_f_standby { get; set; }
    public int day1_f_edited { get; set; }
    public string day1_note { get; set; }

    public DataTable Shifts { get; set; }
    public List<string> Shifts_id { get; set; }
    public List<string> Shifts_value { get; set; }
    public List<string> Shifts_color { get; set; }
    public string Shifts_selected { get; set; }

    public Person(DataTable day1, DataTable shifts)
    {
        string[,] colors = new string[,]
        {
            {"Bisque", "BlueViolet"}, 
            {"Bisque", "BlueViolet"}, 
        };

        foreach (DataRow row in day1.Rows)
        {
            this.day1_id_ca = Convert.ToInt32(row["id_ca"]);
            this.day1_f_shift = Convert.ToInt16(row["field_shift"]);
            this.day1_f_wfh = colors[0,Convert.ToInt16(row["field_wfh"])];
            this.day1_f_standby = colors[1, Convert.ToInt16(row["field_standby"])];
            this.day1_f_edited = Convert.ToInt16(row["edited_by_user_id"]);
            this.day1_note = row["note"].ToString();
        }
//I tried to bind from DataTable, later from list - nothing worked.
        this.Shifts = shifts;

        this.Shifts_id = shifts.AsEnumerable().Select(x => x[0].ToString()).ToList();
        this.Shifts_value = shifts.AsEnumerable().Select(x => x[1].ToString()).ToList();
        this.Shifts_color = shifts.AsEnumerable().Select(x => x[2].ToString()).ToList();
    }
}

1 个答案:

答案 0 :(得分:1)

这应该具有您需要的基本组件:

XAML:

<Window x:Class="ComboBoxInDataGridExample.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:ComboBoxInDataGridExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        d:DataContext="{d:DesignInstance local:MainWindow}">
    <Grid>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Persons}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Monday" Width="auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>

                                <ComboBox x:Name="comboBoxShift" Margin="10,0,0,0" DisplayMemberPath="Description" SelectedValuePath="ID" SelectedValue="{Binding Path=Shifts_selectedId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Height="25" Width="auto" FontSize="10" SelectionChanged="comboBoxShift_SelectionChanged" ItemsSource="{Binding Shifts}">
                                </ComboBox>

                                <Button Name="ButtonStandby" Margin="10 0 0 0"  Content="Standby" Height="25" Width="auto" IsEnabled="True" FontSize="10" FontWeight="UltraBold" Background="{Binding Path=day1_f_standby}">
                                </Button>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls;

namespace ComboBoxInDataGridExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public BindingList<Person> Persons { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Persons = new BindingList<Person>
            {
                new Person{
                    day1_f_standby = "Blue",
                    Shifts = new BindingList<Shift>
                {
                    new Shift{ Description="First shift", ID = 1},
                    new Shift{ Description="Second shift", ID = 2},
                }
                },
                new Person{
                                day1_f_standby = "Red",
                    Shifts = new BindingList<Shift>
                {
                    new Shift{ Description="Early shift", ID = 3},
                    new Shift{ Description="Late shift", ID = 4},
                },
                     Shifts_selectedId = 3
                }
            };
            DataContext = this;
        }

        private void comboBoxShift_DropDownClosed(object sender, EventArgs e)
        {

        }

        private void comboBoxShift_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

数据类:

using System;
using System.ComponentModel;

namespace ComboBoxInDataGridExample
{
    public class Shift
    {
        public string Description { get; set; }
        public int ID { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }

    public class Person
    {
        public int day1_id_ca { get; set; }
        public int day1_f_shift { get; set; }
        public string day1_f_wfh { get; set; }
        public string day1_f_standby { get; set; }
        public int day1_f_edited { get; set; }
        public string day1_note { get; set; }

        public BindingList<Shift> Shifts { get; set; }
        public int Shifts_selectedId { get; set; }

        public Shift SelectedItem { get { return null; } set { } }
    }
}