0

I have a problem with a UserControl I wrote, when I use it in a TabControl of our application. The TabControl is DataBound and uses Templates. On change of the current Tab (per MouseClick) a bound property is set to null. I would like to keep the currently selected item in the ViewModel. If I use a DataGrid or ListBox everything works as espected. The SelectedItem-Property of the ViewModel is not set to null.

Maybe I have to setup my DependencyProperty different? The involved properties are defined like this:

SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(BusinessListEditor), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(BusinessListEditor), new FrameworkPropertyMetadata(null));

This properties are directly bound to a DataGrid inside the UserControl.

<DataGrid x:Name="dgDataGrid"
              ItemsSource="{Binding ItemsSource,
                                    ElementName=ucBusinessListEditor}"
              SelectedItem="{Binding SelectedItem,
                                     ElementName=ucBusinessListEditor}"
              Style="{Binding DataGridStyle,
                              ElementName=ucBusinessListEditor}" />

The question how I can prevent the SelectedItem-Property from changing on a SelectedTab-Change. I tried to analyse this but do not fully understand the case. Somehow the SelectedItemChanged comes from a ItemsChanged of the DataGrid.

Daniel Bişar
  • 2,663
  • 7
  • 32
  • 54

1 Answers1

0

If you change the current tab the old one will be unloaded from visual tree. This means no DataGrid, no SelectedItem.

You could try to stop this behaviour or maybe simpler backup the last SelectedItem from your DP that isn't null in a PropertyChangedCallback.

Community
  • 1
  • 1
LPL
  • 16,827
  • 6
  • 51
  • 95
  • So why the SelectedItem of the ViewModel is not set to null if I use a DataGrid or ListBox, but it is set to null if I use the BusinessListEditor? – Daniel Bişar Apr 26 '12 at 12:59
  • I can't say. I don't know your BusinessListEditor and the structure of your application. – LPL Apr 26 '12 at 13:10
  • For this properties shown above no additional logic exists. Just this two properties plus the DataGrid inside. – Daniel Bişar Apr 26 '12 at 13:15