I have a DataGrid bound to an ObservableCollection. I add cols dynamically. Cols struc is 1st col is TextBlock rest all are Buttons. I have certain issues with the buttons :
I want to set Command for that col, calling a function “OpenTORWindow” with 2 parameters (String, String). I can’t make out how do I set it. Code to add cols is as :
FrameworkElementFactory buttonTemplate = null;
for (int i = 0; i < GlobalUtils.TOR_List.Count; i++)
{
buttonTemplate = new FrameworkElementFactory(typeof(Button));
switch (i) {
case 0:
buttonTemplate.SetBinding(Button.ContentProperty,
new Binding("CLVButtonText"));
break;
case 1:
buttonTemplate.SetBinding(Button.ContentProperty,
new Binding("MKBLButtonText"));
break;
}
buttonTemplate.SetBinding(Button.CommandProperty, new Binding("MyCommand"));
RoutedEventHandler handler = new RoutedEventHandler(OpenNewWindow);
buttonTemplate.AddHandler(Button.ClickEvent, handler, true);
this.seivesTorGrid.Columns.Add(new DataGridTemplateColumn()
{
Header = GlobalUtils.TOR_List[i].TOR_Id,
CellTemplate = new DataTemplate() { VisualTree = buttonTemplate }
});
}
I assign MyCommand with:
MyCommand = new RelayCommand(param => this.OpenWindow(s.SeiveIdSize))
But the MyCommand is never triggered. Then I added AddHandler, that’s working.
Any idea why CommandProperty is not working.
The button you are adding shares the DataContext from the current row in the DataGrid, so when you call ‘MyCommand’, WPF searches the object in TOR_List, and as it probably does not exists, it will not execute.
You can check the output windows to check for binding errors.
To achieve what you want, you’ll have to create the command in the object from which TOR_List is a list for, or use RelativeSource.