Я все еще довольно новичок в WPF и MVVM. Я добавил DataGridComboBoxColumn в DataGrid. Привязка к представлению объекта работает нормально. Однако при повторном открытии экрана после сохранения в выпадающем списке не отображается ранее сохраненное значение (в основном привязка из представления обратно к пользовательскому интерфейсу не работает).
Ниже приводится идея того, что я пытаюсь сделать:
Следующие три класса являются моими взглядами
ViewPosition - это тип класса строк в моей сетке данных (см. XAML ниже). ViewPosition содержит ссылку на ViewPricing.
ViewPricing содержит ссылку на parentSecurity (тип строки).
Безопасность - это безопасность, содержащая свойство Description.
public class ViewPosition : INotifyPropertyChanged
{
private long _securityID;
private long _portfolioID;
private DateTime _positionDate;
private ViewPricing viewPricing;
public ViewPricing Pricing
{
get { return viewPricing; }
set
{
viewPricing= value;
NotifyPropertyChanged();
}
}
}
public class ViewPricing : INotifyPropertyChanged
{
private String parentSecurity;
private decimal quantity;
private decimal price;
private decimal yield;
private decimal spread;
public string ParentSecurity
{
get { return parentSecurity; }
set
{
if (parentSecurity != value)
{
parentSecurity = value;
NotifyPropertyChanged("parentSecurity");
}
}
}
}
public class Security : INotifyPropertyChanged
{
public string Description { get; set; }
}
Вот моя модель взгляда. Получает список всех доступных ценных бумаг.
public class PositionViewModel : INotifyPropertyChanged
{
private List<Security> _securities;
private List<Security> _securities;
public List<Security> Securities
{
get { return _securities; }
set
{
if (_securities != value)
{
_securities = value;
NotifyPropertyChanged();
}
}
}
Наконец, вот мой XAML.
- Я хочу, чтобы пользователь увидел описание безопасности в поле со списком. Вот почему я установил DisplayMemberPath = "Описание".
- После сохранения я хочу, чтобы значение поля со списком было сохранено в Pricing.ParentSecurity. Вот почему я установил SelectedValueBinding и SelectedValuePath, как показано ниже.
В списке ценных бумаг правильно отображается поле со списком. Работает привязка к объекту представления (значение в выпадающем списке сохраняется в Pricing.ParentSecurity). Проблема, с которой я столкнулся, заключается в том, что привязка объекта просмотра к пользовательскому интерфейсу (комбинированное окно) не работает. Если закрыть, то снова откройте мое окно, тогда поле со списком не показывает значение (оно пустое).
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Parent Security" SelectedValueBinding="{Binding Path=Pricing.ParentSecurity, Mode=TwoWay}" SelectedValuePath="Description" DisplayMemberPath="Description"/>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Securities, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<Setter Property="IsReadOnly" Value="True"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Securities, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
Спасибо за любую помощь / предложения, которые вы можете предоставить!