下面有什么比示例更简单的东西吗?我确实有可观察的集合(代码中的“list”)绑定到DataGrid lstLinks
for (int i = 0; i < list.Count ; i++)
{
object rowItem = lstLinks.Items[i] ;
DataGridRow visualItem = (DataGridRow)lstLinks.ItemContainerGenerator.ContainerFromItem(rowItem);
if ( visualItem == null ) break;
if (list[i].Changed)
visualItem.IsSelected = false;
else
visualItem.IsSelected = false;
}
答案 0 :(得分:7)
是的,有一个更简单的解决方案,您只需要将您想要的项目从绑定列表添加到DataGrid SelectedItems集合,请参阅下面的代码:[如果此帖子解决了您的问题,请不要忘记将其标记为答案问题:)]
<Window x:Class="ProgGridSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
new Employee {Code = "E431", Name = "Zuhair Zein"},
new Employee {Code = "E431", Name = "Layla Abdullah"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, add it to your DataGrid SelectedItems collection to
* add the item to the selected rows
*/
if (emp != null)
empDataGrid.SelectedItems.Add(emp);
}
}
答案 1 :(得分:1)
MVVM需要更多的投标解决方案,
但它是MVVM,它完全可测试且易于维护。
答案 2 :(得分:0)
是的,这个解决方案比攻击DataGrid控件更好,如果你只想选择一行,你也可以使用以下代码:
myDataGrid.SelectedItem = item;
其中item是绑定DataGrid的项目之一。
答案 3 :(得分:0)
假设 lstLinks
是 WPF DataGrid
,这会将位置 i
处的项目添加到所选项目:
lstLinks.SelectedItems.Add(lstLinks.Items[i]);
要取消选择所有内容:
lstLinks.SelectedItems.Clear();