WPF:数据网格中按钮的命令绑定
在此示例中,我有两个按钮。标题中的按钮可以工作,但网格中的按钮给我显示如下错误。
<GroupBox DockPanel.Dock="Top" >
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Recent Servers" />
<CheckBox Content="Auto-Refresh" />
<Button Content="Monitor" Command="{Binding MonitorCommand, ElementName=Top}" CommandParameter="{Binding}" />
</StackPanel>
</GroupBox.Header>
<DataGrid CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False" ItemsSource="{Binding ServerHistory}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Machine Name" Binding="{Binding DataPoints[ServerName], Mode=OneWay}" />
<DataGridTextColumn Header="Last Heartbeat" Binding="{Binding DataPoints[LastHeartbeat], Mode=OneWay}"/>
<DataGridTemplateColumn Header="Monitor">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Monitor" Command="{Binding MonitorCommand, ElementName=Top}" CommandParameter="{Binding}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
System.Windows.Data 错误:4:无法找到与引用“ElementName=Top”进行绑定的源。 BindingExpression:Path=MonitorCommand;数据项=空;目标元素是“按钮”(名称=“”);目标属性是“Command”(类型“ICommand”)
In this sample I have two buttons. The button in the header works, but the one in the grid gives me the error show below.
<GroupBox DockPanel.Dock="Top" >
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<Label Content="Recent Servers" />
<CheckBox Content="Auto-Refresh" />
<Button Content="Monitor" Command="{Binding MonitorCommand, ElementName=Top}" CommandParameter="{Binding}" />
</StackPanel>
</GroupBox.Header>
<DataGrid CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False" ItemsSource="{Binding ServerHistory}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Machine Name" Binding="{Binding DataPoints[ServerName], Mode=OneWay}" />
<DataGridTextColumn Header="Last Heartbeat" Binding="{Binding DataPoints[LastHeartbeat], Mode=OneWay}"/>
<DataGridTemplateColumn Header="Monitor">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Monitor" Command="{Binding MonitorCommand, ElementName=Top}" CommandParameter="{Binding}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Top'. BindingExpression:Path=MonitorCommand; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信这是因为您的第二个按钮是作为模板的一部分包含的。相反,使用单击事件,在后面的代码中获取它并尝试确定发送者与数据的关系,然后发出命令触发器。
I believe it's because your second button is enclosed as part of a template. Have a click event instead, grab it in the code behind and try to work out the sender's relationship to your data, then issue the command trigger.