我有一个使用MVVM模式的WPF应用程序。
我有两张表
Customers: CustomerId, CustomerName, CurrencyId
货币:CurrencyId, Description
两个表在主键上使用自动递增,并且在两个CurrencyId列上存在外部关系。
经过一番努力,我可以显示客户列表,单击每个客户,并且我的数据被绑定,但是索引不正确。
Currency表增量从1开始,但ComboBox从0开始,因此基本上对于每个客户,显示的货币描述都是不正确的。
不确定是否需要,但这是我的代码到目前为止。
ViewModel:
public class TestingViewModel : ViewModelBase
{
// Constructor
public TestingViewModel()
{
Customers = GetCustomers();
Currencies = GetCurrencies();
}
private ObservableCollection<Customer> _customers;
public ObservableCollection<Customer> Customers
{
get { return _customers; }
set
{
_customers = value;
RaisePropertyChanged("Customers");
}
}
private ObservableCollection<Currency> _currencies;
public ObservableCollection<Currency> Currencies
{
get { return _currencies; }
set
{
_currencies = value;
RaisePropertyChanged("Currencies");
}
}
private ObservableCollection<Customer> GetCustomers()
{
var dbContext = new DbDataContext();
return new ObservableCollection<Customer> dbContext.Customers.ToList());
}
private ObservableCollection<Currency> GetCurrencies()
{
var dbContext = new DbDataContext();
return new ObservableCollection<Currency>(dbContext.Currencies.ToList());
}
}
视图:<Grid>
<ListView x:Name="LstCustomers" Grid.Column="0" Grid.Row="1"
ItemsSource="{Binding Path=Customers, Mode=Oneway}" IsSynchronizedWithCurrentItem="True" Background="White"
ItemContainerStyle="{StaticResource ListViewItemsStyle}">
<ListView.ItemTemplate>
<DataTemplate >
<TextBlock Text="{Binding Path=CustomerName, Mode=OneTime}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<TextBox x:Name="TbContactName" Width="300" Height="30" Margin="0,-100,0,0"
VerticalAlignment="Center" HorizontalAlignment="Right"
Text="{Binding ElementName=LstCustomers, Path=SelectedItem.ContactName, UpdateSourceTrigger=PropertyChanged}" />
<ComboBox x:Name="combobox" ItemsSource="{Binding Currencies}" Width="300" Height="40" HorizontalAlignment="Right"
DisplayMemberPath="Description"
SelectedValuePath="CurrencyId"
SelectedIndex="{Binding ElementName=LstCustomers, Path=SelectedItem.CurrencyId}" />
</Grid>
在我的代码中是否有不正确的东西,或者我如何解决这个问题?
谢谢,
您依赖于组合框中货币的索引与其CurrencyId相同,这是错误的- CurrencyId是它们在数据库中的id,组合框中货币元素的索引取决于它们在组合框中的顺序。
我将在ViewModel中添加SelectedCustomer和SelectedCurrency属性,并从SelectedCustomer属性setter中更新SelectedCurrency。例如:private Customer _selectedCustomer;
public Customer SelectedCustomer
{
get { return _selectedCustomer; }
set
{
_selectedCustomer = value;
RaisePropertyChanged("SelectedCustomer");
SelectedCurrency = this.Currencies
.FirstOrDefault(x => x.CurrencyId == SelectedCustomer.CurrencyId);
}
}
private Currency _selectedCurrency;
public Currency SelectedCurrency
{
get { return _selectedCurrency; }
set
{
_selectedCurrency = value;
RaisePropertyChanged("SelectedCurrency");
}
}
然后,不做SelectedIndex="{Binding ElementName=LstCustomers, Path=SelectedItem.CurrencyId}"
,像SelectedItem = {Binding SelectedCurrency}
一样绑定它,并对SelectedCustomer做同样的操作。