Search code examples
c#wpfwpfdatagrid

WPF DataGrid not showing selected items when I open a second window


I open a borderless window with ShowDialog() on mouse right click over WPF datagrid. The aim is to give user chance to add selected items to a list. When the dialog window opens the selected items in DataGrid loose the selected "visuals" (in this case the default blue highlight) until the dialog is closed. How do I get around this so user still has a visual clue as to what they have selected.

Code to open dialog =

private void MusicLibrary_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        Point mousePoint = this.PointToScreen(Mouse.GetPosition(this));
        PlayListRClick option = new PlayListRClick();
        option.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
        option.Height = 150;
        option.Width = 100;
        option.Left = mousePoint.X;
        option.Top = mousePoint.Y;
        option.ShowDialog();


        //Get the selected option and add itmes to playlist as needed
        switch (option.choice)
        {
            case RightClickChoice.AddToPlayList:
                IList Items = MusicLibrary.SelectedItems;
                List<MyAlbum> albums = Items.Cast<MyAlbum>().ToList();
                foreach (MyAlbum a in albums)
                {
                    PlayListOb.Add(a);

                }
                break;


        }


    }

Solution

  • The DataGrid will only highlight blue when it has user focus, otherwise it uses a different brush (usally LightGray), so when you dialog opens the DataGrid loses focus and the "Blue" brush is removed.

    When the DataGrid is focused it used SystemColors.HighlightTextBrushKey, and when unfocused it uses SystemColors.InactiveSelectionHighlightBrushKey

    So you could try set the SystemColors.InactiveSelectionHighlightBrushKey to the SystemColors.HighlightColor, this should keep it blue when you open your dialog.

    Example:

    <DataGrid>
        <DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="{x:Static SystemColors.HighlightColor}"/>
        </DataGrid.Resources>
    </DataGrid>
    

    Edit:

    For .NET4.0 and below you may have to use SystemColors.ControlBrushKey instead of SystemColors.InactiveSelectionHighlightBrushKey

    <DataGrid>
        <DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}"/>
        </DataGrid.Resources>
    </DataGrid>