说明:后台代码红色的部分为问题
问题具体描述:设置默认行的代码在Init函数中,也就两行,如下:
void Init() { dataGrid.SelectedIndex = 0; dataGrid.Focus(); }
问题就是,将Init()放入,该xaml对应的.cs中的构造函数,运行的时候不行,设置默认选中行不成功
public MainWindow() { InitializeComponent(); }
但是放到下面两个Load函数中,一个是窗体Load函数,另一个是Datagrid的load函数,这两个函数是在MainWindow的之后执行的,这种先后顺序为什么会影响到Init()中的代码效果
前台Xaml代码:
<Window x:Class="DataGridTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DataGridTest" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> <Grid> <DataGrid x:Name="dataGrid" Height="200" Loaded="dataGrid_Loaded" Margin="0,0,0,119" > <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Name}" Header="名称"/> </DataGrid.Columns> </DataGrid> <Button Height="20" Width="60" Content="button" Margin="367,225,30,54" Click="Button_Click"></Button> </Grid> </Window>
后台C#代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DataGridTest { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<SampleData> sd = new List<SampleData>(); SampleData sampleData = new SampleData(); sampleData.Name = "Jack"; sd.Add(sampleData); sampleData.Name = "Fack"; sd.Add(sampleData); sampleData.Name = "Gack"; sd.Add(sampleData); dataGrid.ItemsSource = sd; } private void Button_Click(object sender, RoutedEventArgs e) { dataGrid.SelectedIndex = 2; dataGrid.Focus(); } void Init() { dataGrid.SelectedIndex = 0; dataGrid.Focus(); } private void Window_Loaded(object sender, RoutedEventArgs e) { } private void dataGrid_Loaded(object sender, RoutedEventArgs e) { Init(); } } public struct SampleData { public string Name { get; set; } } }
表格都还没生成,怎么可能选中,再怎么也要等表格渲染完了,你才可以设置选中行嘛
3Q,是我还没弄清这几个函数的作用