WPF 根据 ObservableCollection<T> 项选择组合框项
Posted
技术标签:
【中文标题】WPF 根据 ObservableCollection<T> 项选择组合框项【英文标题】:WPF select combox item according to ObservableCollection<T> item 【发布时间】:2021-12-23 02:16:48 【问题描述】:我不知道怎么问这个问题,但我会尽力而为。 我有绑定到 GridView 的 ObservableCollection,并且 GridView 有一个带有组合框的列,我需要在用 ObservableCollection 中的数据填充 gridview 以自动从组合框中选择项目。
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
所以,我需要在窗口加载时将TasksList
绑定到数据网格dg
以获取Status
字符串并从组合框中选择项目。
有什么帮助吗?
【问题讨论】:
【参考方案1】:将Record
类的Status
属性类型更改为status
(枚举类型)或将ComboBox
的ItemsSource
属性设置为IEnumerable<string>
:
public override object ProvideValue(IServiceProvider serviceProvider)
return Enum.GetValues(EnumType).Cast<object>().Select(x => x.ToString());
类型必须匹配。您不能将string
属性设置为枚举(enum)值。
【讨论】:
以上是关于WPF 根据 ObservableCollection<T> 项选择组合框项的主要内容,如果未能解决你的问题,请参考以下文章
MainWindow 高度\宽度将根据当前视图 WPF 设置