我正在开发一个C#项目,我有一个包含对象的DataGrid: DataGrid picture
我的主要目标是用户只能选择一个“购买”类型的对象。 (当然多选是真的) 如果他试图选择另一个,什么都不会改变,选择保持不变。 但是,他可以根据需要选择尽可能多的“卖出”类型的对象。
但我的代码似乎不起作用,我怎么能解决这个问题?
代码:
<DataGrid Name="TransactionTableXAML" AutoGenerateColumns="False" ItemsSource="{Binding Path=tableAttributes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectionChanged="TransactionTableXAML_SelectionChanged"/>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public bool boughtSelected = false;
public int currentBoughtIndex;
private void TransactionTableXAML_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
boughtSelected = false;
if(TransactionTableXAML.SelectedItem!=null)
{
var itemsSource = TransactionTableXAML.ItemsSource as IEnumerable;
if (itemsSource != null)
{
foreach (var item in itemsSource)
{
var dataGridRow = TransactionTableXAML.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
var stock = (MyObject)item;
if (boughtSelected == false)
{
if (stock.getTransactionType() == "BUY")
{
currentBoughtIndex = dataGridRow.GetIndex();
}
}
else if(boughtSelected==true && stock.getTransactionType()=="BUY" && currentBoughtIndex!=dataGridRow.GetIndex())
{
dataGridRow.IsSelected = false;
}
}
}
}
}
}