c# - 检查数据网格是否有值
问题描述
我正在开发一个包含 WPF 的 C# 项目。我想知道,如果我能以某种方式检查我的数据网格是否包含某些元素。
例如,我有一个组合框,其 itemsSource 是一些对象列表。现在,当用户从组合框中选择一个项目并按下按钮时
我想禁止用户多次选择同一项目,例如将 MessageBox 与错误消息一起放置。我怎么能那样做?
代码
这个窗口:
public partial class AvioWindowAddNEdit : Window
{
Avio avio;
public enum Stage { ADD, EDIT};
Stage stage;
public AvioWindowAddNEdit(Avio avio, Stage stage = Stage.ADD)
{
InitializeComponent();
this.avio= avio;
this.stage= stage;
textboxCode.DataContext = avio;
comboboxListofFlights.ItemsSource = Aplikacija.Instance.Flights;
comboboxListofFlights.DataContext = avio;
datagridListofFlights.ItemsSource = avio.ListofFlights;
datagridListofFlights.ColumnWidth = new DataGridLength(1, DataGridLengthUnitType.Auto);
if (stage== Stage.EDIT)
{
textboxCode.IsEnabled = false;
}
}
}
将所选项目添加到数据网格的按钮:
private void btnAddFlight_Click(object sender, RoutedEventArgs e)
{
avio.ListOfFlights.Add(comboboxListOfFlights.SelectedItem as Flight);
}
用于加载我所有数据的单例类:
class Aplication
{
public ObservableCollection<User> Users { get; set; }
public ObservableCollection<Airport> Airports { get; set; }
public ObservableCollection<Flight> Flights{ get; set; }
public ObservableCollection<Avio> Avios { get; set; }
public string LoggedInUser { get; set; }
private static Aplication instance = new Aplication();
public static Aplication Instance
{
get
{
return instance;
}
}
private Aplication()
{
Users= new ObservableCollection<User>();
Airports = new ObservableCollection<Airport>();
Flights = new ObservableCollection<Flight>();
Avios= new ObservableCollection<Avio>();
FillInData(); //method where I filled in all of these ObservableCollections
}
}
我的课:
public class Avio : ObservableObject, ICloneable
{
//observableobject is an object where I implemented INotifyPropertyChanged
private string code;
public string Code
{
get { return code; }
set { code= value; OnPropertyChanged("Code"); }
}
private ObservableCollection<Flight> listOfFlights;
public ObservableCollection<Flight> ListOfFlights
{
get { return listOfFlights; }
set { listOfFlights= value; OnPropertyChanged("ListOfFlights"); }
}
private bool active;
public bool Active
{
get { return active; }
set { active= value; OnPropertyChanged("Active"); }
}
public Avio()
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
}
public Avio(string code)
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
Code= code;
}
}
解决方案
您可以使用ObservableCollection作为 DataGrid 的 ItemsSource。这样,您将始终可以通过代码轻松访问数据。查看本教程作为起点(它使用 ListBox 而不是 DataGrid,但它很容易适应 DataGrid)。
推荐阅读
- python - 如果 import matplotlib 不存在,为什么 import urllib 会失败?
- python - 一个 3 维张量如何被两个 2 维张量索引?
- dart - 在颤动中改变按钮的状态
- swift - 没有 UI 元素的 Segue 和 Unwind segue
- swift - Swift - 从 UserDefaults 检索数据后,TableView 中没有显示数据
- c++ - 在 Windows 10 上使用 nuwen MinGW 的 C++17 文件系统
- jenkins - Jenkins SoapUI 请求在 Jenkins 中运行时未收到全局属性
- apache - 安装后如何配置Virtualmin以使用域名访问
- android - 为什么我无法从 Android 中的 Firebase 深层链接 url 获取查询参数?
- python - Python Mock 没有被分配给班级