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());
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With