Wpf 在DataGrid中动态添加的按钮列的CommandProperty不';行不通
我将一个Wpf 在DataGrid中动态添加的按钮列的CommandProperty不';行不通,wpf,button,binding,command,controltemplate,Wpf,Button,Binding,Command,Controltemplate,我将一个数据网格绑定到一个可观察集合。我动态添加col。Cols struc为第1列为文本块其余均为按钮。我对按钮有一些问题: 我想为该列设置命令,用两个参数(字符串,字符串)调用函数“OpenTORWindow”。我搞不懂该怎么设置。添加COL的代码如下所示: FrameworkElementFactory buttonTemplate = null; for (int i = 0; i < GlobalUtils.TOR_List.Count; i++) {
数据网格
绑定到一个可观察集合
。我动态添加col。Cols struc为第1列为文本块其余均为按钮。我对按钮有一些问题:
我想为该列设置命令,用两个参数(字符串,字符串)调用函数“OpenTORWindow”。我搞不懂该怎么设置。添加COL的代码如下所示:
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 }
});
}
FrameworkElementFactory buttonTemplate=null;
for(int i=0;i
我为MyCommand分配以下内容:
MyCommand=newrelaycommand(param=>this.OpenWindow(s.seivedsize))
但是MyCommand永远不会被触发。然后我添加了AddHandler,这很有效。
了解CommandProperty不起作用的原因。您正在添加的按钮共享DataGrid中当前行的DataContext,因此当您调用“MyCommand”时,WPF会在TOR_列表中搜索该对象,因为它可能不存在,所以不会执行。 您可以检查输出窗口以检查绑定错误
要实现您想要的功能,您必须在TOR_List作为列表的对象中创建命令,或者使用RelativeSource。@Deigo,谢谢。好吧,这是在适当的来源,但我只提到了公共MyCommand,而不是作为属性获取;&设置因此它无法找到它。我把它作为财产加了进去,一切都很顺利。