从DataGridTextColumn.Header绑定到Parent.Parent

时间:2013-02-01 08:13:59

标签: c# xaml mvvm binding icommand

通常它应该自动工作,但它不会

XAML:

 <DataGrid AutoGenerateColumns="False" Width="350" IsReadOnly="True" 
                              ItemsSource="{Binding StichwortList}" >
           <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding DisplayName}" Width="350">
                      <DataGridTextColumn.Header>
                            <DockPanel Margin="0" Width="340" HorizontalAlignment="Stretch" LastChildFill="True">
                                  <TextBlock DockPanel.Dock="Left" Margin="0" Text="Name"/>
                                  <Button DockPanel.Dock="Right" Content="-" Margin="0" Width="23" Command="{Binding RemoveStichwortCommand}"/>
                                  <Button DockPanel.Dock="Right" Content="+" Margin="0" Width="23" Command="{Binding AddStichwortCommand}"/>
                                  <Label />
                            </DockPanel>
                      </DataGridTextColumn.Header>
                 </DataGridTextColumn>
           </DataGrid.Columns>
  </DataGrid>

相关代码:

        private RelayCommand _addStichwortCommand;
        public ICommand AddStichwortCommand
        {
            get { return _addStichwortCommand ?? (_addStichwortCommand = new RelayCommand(param => this.OnAddStichwort())); }
        }

        private void OnAddStichwort()
        {
            // some code
        }

        private RelayCommand _removeStichwortCommand;
        public ICommand RemoveStichwortCommand
        {
            get { return _removeStichwortCommand ?? (_removeStichwortCommand = new RelayCommand(param => this.OnRemoveStichwort())); }
        }
private void OnRemoveStichwort()
        {
           // some code
        }

我对此视图的其他绑定有效,我的命令绑定也能正常工作

所以有人可以告诉我,我的绑定有什么问题吗?

修改

哦,我忘记了

全部在UsercontrolDatacontext包含属性以及绑定和命令

Soultion:

DockPanel需要将Datacontext绑定到Usercontrol Datacontext,而Usercontrol需要一个名称

x:Name="uc"

<DockPanel Margin="0" Width="340" HorizontalAlignment="Stretch" LastChildFill="True" DataContext="{Binding ElementName=uc, Path=DataContext}">
     <TextBlock DockPanel.Dock="Left" Margin="0" Text="Name"/>
     <Button DockPanel.Dock="Right" Content="-" Margin="0" Width="23" Command="{Binding RemoveStichwortCommand}"/>
      <Button DockPanel.Dock="Right" Content="+" Margin="0" Width="23" Command="{Binding AddStichwortCommand}"/>
      <Label />
</DockPanel>

如果上述解决方案不起作用,您应该查看此answer

1 个答案:

答案 0 :(得分:1)

您必须在 XAML 中命名UserControl并在绑定中使用它。类似于以下代码:

<UserControl x:Name="uc" >
.
.
.
<Button DockPanel.Dock="Right" Content="-" Margin="0" Width="23" Command="{Binding RemoveStichwortCommand, ElementName=uc}"/>
<Button DockPanel.Dock="Right" Content="+" Margin="0" Width="23" Command="{Binding AddStichwortCommand, ElementName=uc}"/>

希望得到这个帮助。