-2

如何清理先前选择的行?

我有这种方法可以搜索具有给定 ID 的项目。

   private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {

        foreach (MessageFieldViewModel rowItem in Datagrid.ItemsSource)
        {

            if (_mainWindowModel != null)
                _mainWindowModel.SelectedMessageElement = (MessageElementViewModel)e.NewValue;

            var row = Datagrid.ItemContainerGenerator.ContainerFromItem(rowItem) as DataGridRow;

            if (_mainWindowModel != null && _mainWindowModel.SelectedMessageElement != null)
            {
                if (rowItem.Id == _mainWindowModel.SelectedMessageElement.Id)
                {
                    if (row != null)
                        row.Background = Brushes.DarkSalmon;
                }

                row.Background.ClearValue();
            }
            // if (item != null) row.Background.ClearValue(rowItem.Id);
            //  break;
        }

这将选择给定 id 的行。但是如果我想选择另一个 Id 之前的 id 仍然被选中。如何删除以前选择的 ID 并仅显示新选择的 ID?

4

1 回答 1

0

好的,我们开始吧

XAML

<TreeView Name="Tree" Width="50" Height="100"
          ItemsSource="{Binding YourTree}" 
          SelectedItemChanged="Tree_SelectedItemChanged" 
          SelectedValuePath="yourIdProperty"/>
<DataGrid Name="myDatagrid" Width="100" Height="100"
          ItemsSource="{Binding YourList}"
          SelectedItem="{Binding YourSelectedItem,UpdateSourceTrigger=PropertyChanged}"
           SelectedValuePath="Id"/>

代码隐藏

    private void Tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        var tree = sender as TreeView;
        myDatagrid.SelectedValue = tree.SelectedValue;
    }

视图模型

    public List<yourClass> YourList { get; set; }

    private yourClass yourSelectedItem;
    public yourClass YourSelectedItem
    {
        get { return yourSelectedItem; }
        set
        {
            yourSelectedItem = value;
            OnPropertyChanged("YourSelectedItem");
        }
    }

您需要设置SelectedValuePath基于您的属性,它代表您的 Id 但不像字符串那样作为示例"Id"

于 2013-06-14T22:14:50.057 回答