数据网格选定索引绑定在 XAML 中不起作用



问题摘要:XAML是否有办法确保我的datagrid组件在对SelectedIndex属性上启动绑定之前已充分加载?


我的ViewModel是这样的。我正在使用MVVM-Light通知更改的视图。每当从服务器更新时,我将新型号传递给SetData()

public class MyViewModel : ViewModelBase
{
    public void SetData(DataModel model)
    {                
        Data = model.Data; //Array of 75 DataObjects
        DataIndex = model.Index; //int between 0 and 74
    }
    // Array to Bind to Datagrid ItemsSource
    public DataObject[] Data 
    {
        get { return _data; }
        private set
        {
            if (_data!= value)
            {
                _data= value;
                RaisePropertyChanged("Data");
            }
        }
    }
    private DataObject[] _data;
    // Int to Bind to Datagrid SelectedIndex
    public int DataIndex
    {
        get { return _index; }
        private set
        {
            if (_index != value)
            {
                _index = value;
                RaisePropertyChanged("DataIndex");
            }
        }
    }
    private int _index;
}

视图看起来像这样:

<Application.Resources>
    <ResourceDictionary>
        <core:ViewModelLocator x:Key="Locator" />
    </ResourceDictionary>
</Application.Resources>
<DataGrid ItemsSource="{Binding MyViewModel.Data, Source={StaticResource Locator}}"
          SelectedIndex="{Binding MyViewModel.DataIndex, Source={StaticResource Locator}, Mode=OneWay}"
          AutoGenerateColumns="True"/>

我的问题是,我的datagrid上都没有选择所有行。所有数据都正确显示在网格中,但该行未选择。我已经检查了属性,并确认数组长度为75,而DataIndex是0到74之间的int。


似乎是因为设置绑定时尚未完成datagrid的加载。在加载组件后,我可以通过初始化绑定来证明这一点。在这种情况下,一切都按预期工作,并且我所选的项目正确显示:

<DataGrid x:Name="MyDataGrid" Loaded="OnDataGridLoaded"
          ItemsSource="{Binding MyViewModel.Data, Source={StaticResource Locator}}"
          AutoGenerateColumns="True"/>
private void OnDataGridLoaded(object sender, RoutedEventArgs e)
{
    Binding b = new Binding("DataIndex");
    b.Source = Locator.MyViewModel.Data;
    MyDataGrid.SetBinding(DataGrid.SelectedIndexProperty, b);
}

我不必这样做,因为,您知道,代码。那么,是否可以仅使用XAML来解决此问题?这是我到目前为止尝试过的(哪些都不适合我):

  • 将SelectedIndex绑定到我的ViewModel上的int属性(如上所示)
  • 将SelectedItem绑定到我的ViewModel上的DataObject属性(相同结果)
  • 绑定选择的value和selected路径至我的 DataObject的属性(实际上仅在第一个实例中起作用。问题是我有此datagrid组件的多个实例,出于某种原因,这仅在第一次实例上起作用)
  • 与观测值截面而不是数组结合(尝试了上述所有3种具有观测值的方法,并且每个方法都得到了相同的结果)
  • 通过将其包装在Dispatcher.Invoke的呼叫中来延迟更改通知。这无济于事,因为该组件没有立即在视图中。
  • 在XAML中创建绑定,然后在加载函数中更新目标。MyDataGrid.GetBindingExpression(DataGrid.SelectedIndexProperty).UpdateTarget();

我最初的问题缺少引起问题的信息。当绑定源是静态链接时,似乎有一个WPF错误。如果我将 DataIndex属性移至组件的数据tacontext中,则可以正常工作。

我不会这样做,因为数据在多个实例之间共享。我不需要多个数据实例,只有组件。因此,我将作为Microsoft错误将其右转,并使用代码工作。

我将打开问题,以防任何人对此错误有解决方案。

最新更新