问题描述
我有一个 viewmodel(父),它是两个用户控件(比如 UCdatagrid 和 UCEditControls)的父级,用户控件没有视图模型并且使用父视图模型 DataContext。
我想要做的是使用由文本框和组合框组成的 UCEditControls 对 UCDatagrid 执行 CRUD 操作。组合框预先填充了数据。
到目前为止,除了组合框链接之外,我的一切都在工作。文本框(代码)在数据网格行选择上正确填充。当用户单击数据网格行时,我希望采用相应的类型列值并将其显示为类型组合框中的选定项目,以便进行更新。
我正在使用 Caliburn Micro。
Parentviewmodel.cs
public class ConductorProductviewmodel : Screen
{
private readonly IDataConnection _connect;
private ProductModel _selectedProduct;
public ProductModel SelectedProduct
{
get { return _selectedProduct; }
set
{
_selectedProduct = value;
NotifyOfPropertyChange(() => SelectedProduct);
}
}
private TypeModel _selectedType;
public TypeModel SelectedType
{
get { return _selectedType; }
set { _selectedType = value; NotifyOfPropertyChange(() => SelectedType); }
}
private BindableCollection<ProductModel> _productList;
public BindableCollection<ProductModel> ProductList
{
get { return _productList; }
set { _productList = value; NotifyOfPropertyChange(() => ProductList); }
}
private BindableCollection<TypeModel> _types;
public BindableCollection<TypeModel> Types
{
get { return _types; }
set { _types = value; NotifyOfPropertyChange(() => Types); }
}
public ConductorProductviewmodel(IDataConnection connect)
{
_connect = connect;
GetProducts();
LoadComboBoxLists();
}
private void LoadComboBoxLists()
{
Types = new BindableCollection<TypeModel>(_connect.Types_GetAll());
}
private async void GetProducts()
{
var allProducts = await _connect.Products_GetAll();
ProductList = new BindableCollection<ProductModel>(allProducts);
}
}
DataGrid.Xaml
<UserControl x:Class="...>
<Grid>
<DataGrid ItemsSource="{Binding ProductList}" SelectedItem="{Binding SelectedProduct}">
<DataGrid.Columns>
<DataGridTextColumn Header="Code" Binding="{Binding Code}"/>
<DataGridTextColumn Header="Type" Binding="{Binding Type}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</UserControl>
EditControls.Xaml
<UserControl x:Class="...>
<Grid>
<TextBox Text="{Binding SelectedProduct.Code}" />
<ComboBox Name="TypeCB" ItemsSource="{Binding Types}"
SelectedItem={Binding SelectedType}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Type}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</UserControl>
我试图实现的目标的图像 https://i.stack.imgur.com/OGPzP.png
解决方法
找到有关解决方案的帮助
在我添加的 SelectedProduct 属性中
public ProductModel SelectedProduct
{
get { return _selectedProduct; }
set
{
_selectedProduct = value;
var indexOfType = Types.Select((TypeModel,index) => new { TypeModel,index }).First(x => x.TypeModel.Type == value.Type).index;
TypeIndex = indexOfType;
NotifyOfPropertyChange(() => SelectedProduct);
}
}
然后我将组合框上的 SelectedIndex 绑定到一个名为 TypeIndex 的新属性。
现在,无论何时选择数据网格行,它都会找到数据网格“类型”列值并匹配类型的组合框列表并获取索引号。此索引值传递给 TypeIndex。