簡體   English   中英

Datagrid SelectedIndex綁定在XAML中不起作用

[英]Datagrid SelectedIndex binding won't work in XAML

問題摘要:XAML中是否有一種方法可以確保在對SelectedIndex屬性啟動綁定之前,我的DataGrid組件已完全加載?


我的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上沒有選擇任何行。 所有數據均正確顯示在網格中,但未選中該行。 我檢查了屬性,並確認Array的長度為75, DataIndex為0到74之間的整數。


似乎是因為設置綁定后,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屬性(相同的結果)
  • 將SelectedValue和SelectedPath綁定到我的DataObject的屬性(這實際上僅在第一個實例中有效。問題是我有該Datagrid組件的多個實例,並且由於某種原因,它僅在第一個實例上有效)
  • 綁定到ObservableCollection而不是Array(將上述3種方法都用ObservableCollection進行嘗試,並獲得相同的結果)
  • 通過將更改包裝在對Dispatcher.Invoke的調用中來延遲更改通知。 這沒有幫助,因為沒有立即看到該組件。
  • 在XAML中創建綁定,然后在Loaded函數中更新目標。 MyDataGrid.GetBindingExpression(DataGrid.SelectedIndexProperty).UpdateTarget();

我最初的問題缺少引起問題的信息。 當綁定源是靜態鏈接時,似乎存在WPF錯誤。 如果將DataIndex屬性移到組件的DataContext中,則它將正常工作。

但是,我不會這樣做,因為數據是在多個實例之間共享的。 我不需要數據的多個實例,而只需要組件。 因此,我將其作為Microsoft Bug加以糾正,並使用隱藏代碼解決。

如果有人對此錯誤有解決方案,我將開放問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM