对于我正在处理的i项目,我需要能够例如选择grid1中的第一行并自动在grid2中选择第一行,以便同时在两个网格中选择一行。
已尝试过的内容
我创建了一种在gids中设置所选项目的方法
private void SyncDataGridItemSelection(int number)
{
//sync pricegrid with printertick grid
if (number == 1)
{
int printertickselection = PrinterTicksGrid.SelectedIndex;
//detachs change event
PrinterPriceGrid.SelectionChanged -= (PrinterPriceGrid_SelectionChanged);
//change printerpricegrid selection
PrinterPriceGrid.SelectedIndex = printertickselection;
//attach change event
PrinterPriceGrid.SelectionChanged += (PrinterPriceGrid_SelectionChanged);
}
//sync printertick grid with price grid
else if (number == 2)
{
int printerpriceselection = PrinterPriceGrid.SelectedIndex;
//detachs change event
PrinterTicksGrid.SelectionChanged -= (PrinterTicksGrid_SelectionChanged);
//change PrinterTicksgrid selection
PrinterTicksGrid.SelectedIndex = printerpriceselection;
//attach change event
PrinterTicksGrid.SelectionChanged += (PrinterTicksGrid_SelectionChanged);
}
}
我还查看了MSDN中涉及焦点的文档,但没有成功。
GUI已经到位,因此重写不是一个选项
这甚至可以做到,如果是这样的话?
答案 0 :(得分:1)
问题不明确。如果始终选择相同的行,则可以将所有数据放在一个数据网格中,除非您需要特定的布局。但是,让我试着解决你的问题。您可以将两种选择类型合并为一个类。两个Datagrids可以相互连接,而无需使用经典事件。解决方案看起来像这样:
XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="229.584" Width="270.818">
<Grid>
<DataGrid AutoGenerateColumns="False" Name="DG1" HorizontalAlignment="Left" Height="190" Margin="10,0,0,0" VerticalAlignment="Top" Width="116" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Data A" Binding="{Binding AData.data}"/>
</DataGrid.Columns>
</DataGrid>
<DataGrid AutoGenerateColumns="False" Name="DG2" HorizontalAlignment="Left" Height="190" Margin="131,0,0,0" VerticalAlignment="Top" Width="116" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Data B" Binding="{Binding BData.data}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
C#源代码
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
namespace WpfApplication2 {
public class A {
public int data { get; private set; }
public A(int x) { data = x; }
}
public class B {
public string data { get; private set; }
public B(string x) { data = x; }
}
public class C {
public A AData { get; set; }
public B BData { get; set; }
}
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
List<A> lIntegers = new List<A>() { new A(1), new A(2), new A(3), new A(4) };
List<B> lStrings = new List<B>() { new B("a"), new B("b"), new B("c"), new B("d") };
List<C> lParent = new List<C>();
for (int i = 0; i < 4; i++) {
C c = new C();
lParent.Add(c);
c.AData = lIntegers[i];
c.BData = lStrings[i];
}
DG1.DataContext = lParent;
DG2.DataContext = lParent;
}
}
}
www.ohta.de