在xaml中设置datagrid突出显示的单元格

时间:2014-02-25 08:48:03

标签: c# wpf data-binding wpfdatagrid

我的应用程序中有一个DataGrid和一个ListView。 ListView提供有关datagrid所选项的信息。我在该ListView中放置了一个HyperLink,它应该将datagrid的选定项目更改为当前所选项目的“父”。

我的方法是在我的代码中设置SelectedItem。一切都很好,但数据网格没有突出显示新选择的项目。但我可以清楚地看到它被选中,因为它的灰色背景颜色。是否可以通过编程方式设置突出显示的单元格?

<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 个答案:

答案 0 :(得分:0)

您遇到的问题是所选的行/单元格没有聚焦,因为焦点仍在listView项目中。你可以做的是在xaml中设置DataGridCell元素的样式。这是一小段代码,用于演示:

<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>

这里是viewModel部分:

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
}

演示对象类:

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

和一些命令类:

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
}

确保添加View的DataContext,以便它知道您的ViewModel:

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

我希望这可以帮助您获得理想的效果。