开发者

Silverlight DataGrid binding issues after refreshing or setting selectedIndex=-1

开发者 https://www.devze.com 2023-01-29 03:16 出处:网络
I have a datagrid and a combobox on the form.The combobox is bound to the selectedItem of the datagrid.

I have a datagrid and a combobox on the form. The combobox is bound to the selectedItem of the datagrid.

I load things fine and if i select different rows the combobox is updated correcly.

If however I set datagrid.selectedIndex=-1 after it loads (so that the first row is not selected) the combobox binding no longer works. This is a problem.

I also have another scenario where the exact thing occurs. If i filter the datagrid, the binding to the combobox also stops working.

I am binding the datagrid to开发者_如何学Python a CollectionViewSource like the following where _codes is an ObservableCollection

            _ocvsCode = (CollectionViewSource)this.Resources["cvsCode"];
            _ocvsCode.Source = _codes;                
            dataGrid1.ItemsSource = _ocvsCode.View;

I don't know why the binding to the combobox is failing after some operation on the datagrid.


The appropriate solution in this case is to bind the datagrid selecteditem to some variable, and to then bind the other controls to that variable as well. It is generally bad practice to bind UIElement properties directly to other UIElement properties. This will also make debugging the problem you seem to be having with coercing the selecteditem property to the combo-box.


I have come across the same problem, where a ComboBox is bound to a the value of the SelectedItem of a DataGrid.

The ComboBox control breaks when the data it is binding becomes null, and never recovers. I'm not sure why that is, but it seems to me to be a bug. When the DataGrid sorts a column, it first sets its SelectedItem to null, performs the sort, and then resets SelectedItem to the original value. When the SelectedItem becomes null, the ComboBox breaks.

Here's my work around:

Create a SelectedItem property on your class that is being used for the DataContext. Perform a check on the setter that prevents it from being set to null. Bind against this property with your DataGrid and ComboBox.

public YourItem SelectedItem
{
    get { return _selectedItem; }
    set
    {
        if (value == _selectedItem || value == null)
            return;

        _selectedItem = value;
        RaisePropertyChanged("SelectedItem");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消