0

I have a DataGrid and a ListView in my application. The ListView provides information about the datagrid's selected item. I put a HyperLink in that ListView that should change the datagrid's selected item to the "parent" of the currently selected item.

My approach is to set SelectedItemin my code behind. Everything works quite well but the datagrid doesn't highlight the new selected item. But I can clearly see it is selected because off its gray background color. Is it possible to set the highlighted cell programmatically?

<ListView>
    <TextBlock Text="{Binding SelectedParameter.Definition.Name, StringFormat=Name: {0:C}}" 
               TextWrapping="Wrap"/>
    <TextBlock Text="{Binding SelectedParameter.Definition.Type, StringFormat=Datentyp: {0:C}}" 
                               TextWrapping="Wrap"/>
               TextWrapping="Wrap"/>
    <Hyperlink Command="{Binding GoToMasterParameterCommand}">
         Masterparameter
    </Hyperlink>
</ListView>

<DataGrid Name="m_DataGrid" 
              ItemsSource="{Binding Path=Parameters}" 
              SelectedItem="{Binding SelectedParameter}" 
              SelectionMode="Single" 
              AutoGenerateColumns="False" 
              TargetUpdated="m_ParameterDataGrid_TargetUpdated">
        <DataGrid.Columns>
            <DataGridTextColumn 
                Header="ID" 
                Binding="{Binding Id}" 
                IsReadOnly="True"/>
            <DataGridTextColumn 
                Header="Value" 
                Binding="{Binding Value.CurrentInternalValue, NotifyOnTargetUpdated=True}"
        </DataGrid.Columns>
    </DataGrid>

internal void GoToMasterParameter()
{
    string parentId = GetParentId(this.SelectedParameter);
    this.SelectedParameter = this.Parameters.Single(item => item.Id == parentId);
}

1 Answer 1

0

The problem you have is that the selected rows/cells are not focused as the focus is still in your listView item. What you could do is style the DataGridCell element in xaml. Here is a small piece of code that demonstrate this:

<Window.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Red"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <DataGrid ItemsSource="{Binding Tests}" 
              SelectedItem="{Binding GridSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              SelectedIndex="{Binding SelectedGridIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

</DataGrid>
    <Button Command="{Binding ChangeSelectedItemCommand}" 
            Content="Change Grid Selected item" 
            Grid.Column="1" 
            VerticalAlignment="Top"/>
</Grid>

and here the viewModel part:

public class MainWindowViewModel : INotifyPropertyChanged
{
    #region Private members

    private List<TestClass> _tests;
    private TestClass _gridSelectedItem;
    private ICommand _changeSelectedItemCommand;
    private int _selectedGridIndex;
    #endregion

    #region Constructor

    public MainWindowViewModel()
    {
        Tests = new List<TestClass>();
        for (int i = 0; i < 25; i++)
        {
            TestClass testClass= new TestClass {Name = "Name " + i, Title = "Title" + i};
            Tests.Add(testClass);
        }
    }

    #endregion

    #region Public properties
    public List<TestClass> Tests
    {
        get { return _tests; }
        set
        {
            _tests = value;
            OnPropertyChanged("Tests");
        }
    }

    public TestClass GridSelectedItem
    {
        get { return _gridSelectedItem; }
        set
        {
            _gridSelectedItem = value;
            OnPropertyChanged("GridSelectedItem");
        }
    }

    public int SelectedGridIndex
    {
        get { return _selectedGridIndex; }
        set
        {
            _selectedGridIndex = value;
            OnPropertyChanged("SelectedGridIndex");
        }
    }

    #endregion

    public ICommand ChangeSelectedItemCommand
    {
        get { return _changeSelectedItemCommand ?? (_changeSelectedItemCommand = new  SimpleCommand(p => ChangeSelectedGridItem())); }
    }

    private void ChangeSelectedGridItem()
    {
        SelectedGridIndex++;
    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

the demo objects class:

public class TestClass
{
    public string Title { get; set; }
    public string Name { get; set; }
}

and some command class:

public class SimpleCommand : ICommand
{

    private readonly Predicate<object> _canExecuteDelegate;

    private readonly Action<object> _executeDelegate;

    #region Constructors

    public SimpleCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public SimpleCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
        {
            throw new ArgumentNullException("execute");
        }

        _executeDelegate = execute;
        _canExecuteDelegate = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    public virtual bool CanExecute(object parameter)
    {
        return _canExecuteDelegate == null || _canExecuteDelegate(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _executeDelegate(parameter);
    }

    #endregion
}

Make sure to add the DataContext of the View so that it knows about your ViewModel:

 public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }

I hope this helps you obtain the desired effect.

2
  • I think I'm missing something. This snippet doesn't seem to manipulate the focus logic at all. I did quite a similar approach. The data binding updates the datagrid right when I press the link which edits my SelectedItem property. So I expect there to be a possibility to set FocusedItem with data binding Feb 25, 2014 at 15:48
  • this snippet affects the Background of the selected item. You could change only the background color and remain with the focus on the clicked item, or get the real DataGridCell or DataGridRow and pass it to a converter where you could set the .Focus() property on the real GUI object. This would move the focus from the listview item to the DataGridRow/Cell Feb 25, 2014 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.