Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Datacontext from binded user control

I have build a dynamic UserControl from an ObservableCollection as follows...

 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>

But how can I access the DataContext from C# code?

For example say I want to delete the UserControl with a close button in itself, I need at least access ControleData.ComputerName value then remove it from Mainform.ListControleMachine.

I can't find the best practice for achieve this and play with my data in UserControl code.

The remove button code is like this i think (with hard coded value)

  Genkai.ListControleMachine.Remove(Genkai.ListControleMachine.Where(X => X.ComputerName == "M57095").Single());
like image 328
Zwan Avatar asked Nov 08 '22 19:11

Zwan


1 Answers

i finaly found that my DataContext was not yet initialized at start that why i got error so i had to wait for the datacontext first: here code for correction

     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);
        }
like image 97
Zwan Avatar answered Nov 15 '22 12:11

Zwan