У меня есть XDocument, прочитанный из xml-файла:
public ObservableCollection<Product> GetProducts()
{
ObservableCollection<Product> _products = new ObservableCollection<Product>();
XDocument doc = XDocument.Load(@".\Config\MCU.xml");
foreach (XElement productRow in doc.Root.Elements("MCU"))
{
var m = new Product(productRow.Element("MCUName").Value, Convert.ToUInt32(productRow.Element("MCUNumber").Value), Convert.ToUInt32(productRow.Element("FlashAddress").Value),
Convert.ToUInt32(productRow.Element("PageCount").Value), Convert.ToUInt32(productRow.Element("PageSize").Value), productRow.Element("BinFile").Value,
Convert.ToUInt32(productRow.Element("RAMCodeAdd").Value), Convert.ToUInt32(productRow.Element("MainCR").Value), Convert.ToUInt32(productRow.Element("CRTrimmingAdd").Value),
Convert.ToUInt32(productRow.Element("CRTrimmingLength").Value), Convert.ToUInt32(productRow.Element("UIDAdd").Value), Convert.ToByte(productRow.Element("UIDLength").Value),
productRow.Element("UID").Value, productRow.Element("UserArea").Value);
_products.Add(m);
}
return _products;
}
Теперь я хочу связать XElement MCUName
со списком:
<ComboBox x:Name="cb_MCUType" SelectedItem="{Binding MCUName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
ItemsSouce в коде позади:
public MainWindow()
{
InitializeComponent();
cb_MCUType.ItemsSource = App.ProductDb.GetProducts();
}
Но это не работает, поле со списком заполняет Product
, как мне это исправить? Спасибо!
Обновлять:
Спасибо за ответы. Как вы предложили, теперь я хотел бы написать это в MVVM, поэтому я меняю исходный код:
XAML:
<ComboBox x:Name="cb_MCUType" ItemsSource="{Binding ProductsList}" SelectedValue="{Binding SelectedProduct}" DisplayMemberPath="MCUName" />
Модель представления:
public class MainViewModel : INotifyPropertyChanged
{
private ProductDB pd = new ProductDB();
public MainViewModel()
{
DefaultValue_Load();
}
public ObservableCollection<Product> ProductsList { get; set; }
private Product _selectedProduct;
public Product SelectedProduct
{
get { return _selectedProduct; }
set
{
_selectedProduct = value;
NotifyPropertyChanged("SelectedProduct");
}
}
public void DefaultValue_Load()
{
ProductsList = new ObservableCollectioin<Product>(pd.GetProducts());
}
}