我已经从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);
}
XAML
<ItemsControl x:Name="icTodoList" ItemsSource="{Binding ListControleMachine}" >
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:ControlMachineII}">
<local:ControlMachineII />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但是我怎样才能从C#代码中访问DataContext呢?
比如说,我想删除一个带有关闭按钮的UserControl,我至少需要访问ControleData.ComputerName的值,然后将其从Mainform.ListControleMachine中移除。
我找不到最佳实践来完成这个目标并在UserControl代码中操作我的数据。
删除按钮代码应该像这样(使用硬编码的值):
Genkai.ListControleMachine.Remove(Genkai.ListControleMachine.Where(X => X.ComputerName == "M57095").Single());