gpt4 book ai didi

WPF DataGrid 编程多行选择

转载 作者:行者123 更新时间:2023-12-04 17:59:00 25 4
gpt4 key购买 nike

有什么比下面的示例更简单的吗?我确实有绑定(bind)到 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;

}

最佳答案

萨拉姆麦克米特 :)

是的,有一个更简单的解决方案,您只需将您想要的项目从绑定(bind)列表添加到您的 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);
}
}

关于WPF DataGrid 编程多行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2496751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com