Home > Software engineering >  WPF select combox item according to ObservableCollection<T> item
WPF select combox item according to ObservableCollection<T> item

Time:11-11

I don't know how to ask this question but I will try my best. I have ObservableCollection that is bind to GridView and that GridView has a column with combobox and I need while filling the gridview with the data from ObservableCollection to automatically select the item from combobox.

XAML

<DataGrid x:Name="dg" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Date"></DataGridTextColumn>
                    <DataGridTextColumn Header="Description"></DataGridTextColumn>
                    <DataGridTemplateColumn Header="Status" Width="100">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox Name="cb" SelectedItem="{Binding Path=Status}" SelectionChanged="cb_SelectionChanged" ItemsSource="{Binding Source={local:EnumBindingSourceExtention {x:Type local:status}}}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>

MainWindow.xaml.cs

    public partial class MainWindow : Window
    {
        public ObservableCollection<Record> TasksList = new ObservableCollection<Record>();
        public string DbDoc;
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        private void AddRecord(Record task)
        {
            TasksList.Add(task);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DbDoc = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "records.xml");
            if (File.Exists(DbDoc))
            {
                using (StreamReader reader = new StreamReader(DbDoc))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Records));
                    Records records = (Records)serializer.Deserialize(reader);
                    records.RecordsList.ForEach(a=>TasksList.Add(a));
                    dg.ItemsSource = TasksList;
                }
            }
        }
    }
    [XmlRoot("Records")]
    public class Records
    {
        [XmlElement("Record", typeof(Record))]
        public List<Record> RecordsList { get; set; }
    }
    public class Record
    {
        [XmlElement("Date")]
        public string Date { get; set; }
        [XmlElement("Description")]
        public string Description { get; set; }
        [XmlElement("Status")]
        public string Status { get; set; }

    }
        public class EnumBindingSourceExtention : MarkupExtension
    {
        public Type EnumType { get; private set; }

        public EnumBindingSourceExtention(Type enumType)
        {
            if (enumType == null || !enumType.IsEnum)
            {
                throw new Exception("EnumType is null or not EnumType");
            }
            this.EnumType = enumType;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enum.GetValues(EnumType);
        }
    }
    public enum status
    {
        New,
        Old
    }

so, I need in window loading while binding the TasksList to the datagrid dg to also get the Status string and select the item from combobox.

Any help?

CodePudding user response:

Change the type of the Status property of the Record class to status (the enum type) or set the ItemsSource property of the ComboBox to an IEnumerable<string>:

public override object ProvideValue(IServiceProvider serviceProvider)
{
    return Enum.GetValues(EnumType).Cast<object>().Select(x => x.ToString());
}

The types must match. You cannot set a string property to an enumeration (enum) value.

  • Related