从绑定的用户控件访问数据上下文

Zwa*_*wan 5 c# wpf binding user-controls mvvm

我已经从 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)

Zwa*_*wan 1

我最终发现我的 DataContext 在开始时尚未初始化,这就是为什么我收到错误,所以我必须先等待 datacontext:这里是更正代码

     public ControlMachineII()
            {
                InitializeComponent();
                DataContextChanged += new DependencyPropertyChangedEventHandler(ControlMachineII_DataContextChanged);


            }

   private void ControlMachineII_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            string compname = (this.DataContext as Model.Model.ControleData).ComputerName;
            Console.WriteLine("DataContext initialized computername :" +compname);
        }
Run Code Online (Sandbox Code Playgroud)