I have application with toolbar (Add and Delete commands) and TabControl. There is VariableGrid control in each tabItem of TabControl.
look image at: http://trueimages.ru/view/cNFyf
<DockPanel >
<ToolBarTray DockPanel.Dock="Top">
<ToolBar>
<Button Command="{x:Static VariableGrid:VariableGrid.AddRowCommand}"/>
<Button Content="Delete" Command="ApplicationCommands.Delete" />
</ToolBar>
</ToolBarTray>
<TabControl x:Name="tc">
<TabItem Header="Tab 1">
<vg:VariableGrid ItemsSource="{Binding Items1, Mode=TwoWay}"/> </TabItem>
<TabItem Header="Tab 2">
<vg:VariableGrid ItemsSource="{Binding Items2, Mode=TwoWay}"/>
</TabItem>
</TabControl>
<DockPanel >
Toolbar commands are implemented in my control:
public partial class VariableGrid : DataGrid, INotifyPropertyChanged
{
public static RoutedCommand AddRowCommand = new RoutedCommand();
public VariableGrid()
{
this.CommandBindings.Add(new CommandBinding(VariableGrid.AddRowCommand, AddRow));
this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, R emoveRow, CanRemoveRow));
}
private void AddRow(object sender, ExecutedRoutedEventArgs e)
{
…
}
private void RemoveRow(object sender, ExecutedRoutedEventArgs e)
{
…
}
private void CanRemoveRow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (SelectedItems.Count > 0);
}
}
There are few cases when commands in toolbar are disabled:
- when application is running
- when I click on gray field of DataGrid
- when DataGrid is empty
When any row of DataGrid is selected - commands of toolbar are becoming active.
Can you help me with my issue? What CommandTarget of toolbar buttons should I set?
PS: There are two VariableGrids in my application. Thats why I can't set CommandTarget as "{Binding ElementName=variableGrid}". I think it should be set to FocusedElement. But I don't know how to do this.
WPF should be calling your
CanRemoveRowmethod every once in a while to check if it is ok to remove a row. You should put a Boolean condition in this method that will answer that question. If you want similar functionality for yourAddRowCommand, add aCanAddRowmethod where you bind theAddRowCommand.You may want to read the Commanding Overview at MSDN.
UPDATE >>>
Oh... do you want to know what code to use for these disabled conditions? I'll assume so:
when application is running
I'm guessing you mean 'when application is busy'... add a Boolean property named
IsBusy, set it to true when the application performs any long running processes, then add!IsBusyinto your method condition.when I click on gray field of DataGrid
when DataGrid is empty
Both of these conditions can be judged using the
SelectedItemproperty of theDataGridby adding&& dataGrid.SelectedItem != nullinto your method condition.Therefore, you want something like the following: