我已经从 ObservableCollection 构建了一个动态 UserControl 如下...
public static ObservableCollection<Model.Model.ControleData> ListControleMachine = new ObservableCollection<Model.Model.ControleData>();
public Genkai(string Autorisation) {
InitializeComponent();
DataContext = this;
icTodoList.ItemsSource = ListControleMachine;
Model.Model.ControleData v = new Model.Model.ControleData();
v.ComputerName = "M57095";
v.ImportSource = "LOAD";
ListControleMachine.Add(v);
}
Run Code Online (Sandbox Code Playgroud)
XAML
<ItemsControl x:Name="icTodoList" ItemsSource="{Binding ListControleMachine}" >
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:ControlMachineII}">
<local:ControlMachineII />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
但是如何从 C# 代码访问 DataContext?
例如,假设我想删除带有关闭按钮的 UserControl,我至少需要访问 ControleData.ComputerName 值,然后从 Mainform.ListControleMachine 中删除它。
我找不到实现这一点的最佳实践,并在 UserControl 代码中使用我的数据。
我认为删除按钮代码是这样的(带有硬编码值)
Genkai.ListControleMachine.Remove(Genkai.ListControleMachine.Where(X => X.ComputerName == "M57095").Single());
Run Code Online (Sandbox Code Playgroud)