This is a migrated thread and some comments may be shown as answers.

Add tab item with TargetInvocationException

1 Answer 57 Views
TabControl
This is a migrated thread and some comments may be shown as answers.
linnet
Top achievements
Rank 1
linnet asked on 01 Apr 2014, 02:46 AM
Hi!
I'm using RadTabControl and RadTreeView to create my project.
I want to click the tree node to add a tab item in RadTabControl.
When I click the tree node to add a tab item (once or twice) or select other tabs, TargetInvocationException will happen.

Here is the information:
{System.Reflection.TargetInvocationException: Exception thrown by the target of an invocation. ---> System.ArgumentException: Invalid parameter used.
      MS.Internal.XcpImports.CheckHResult(UInt32 hr)
      MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, DependencyObject doh)
      MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj)
      System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
      System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue)
      System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
      System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
      System.Windows.Data.BindingExpression.SendDataToTarget()
      System.Windows.Data.BindingExpression.SourceAcquired()
      System.Windows.Data.Debugging.BindingBreakPoint.<>c__DisplayClass1.<BreakOnSingleType>b__0()
   
      System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
      System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
      System.Delegate.DynamicInvokeImpl(Object[] args)
      System.Delegate.DynamicInvoke(Object[] args)
      MainPagexaml_3.BindingOperation_84_36(Object BindingState, Action )}

Here is my code:

"MainPage.xaml"
<UserControl x:Class="sl_639387_AddTabItem.MainPage"
        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <Style x:Key="CloseButton" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid Background="Transparent" Width="14" Height="14">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal" />
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames
                                                    Storyboard.TargetProperty="(UIElement.Visibility)"
                                                    Storyboard.TargetName="FocusEllipse">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ColorAnimation Duration="0" To="#FFDC3030"
                                                    Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
                                                    Storyboard.TargetName="FocusEllipse" />
                                            <ColorAnimation Duration="0" To="White"
                                                    Storyboard.TargetProperty="(Shape.Stroke).(SolidColorBrush.Color)"
                                                    Storyboard.TargetName="path" />
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames
                                                    Storyboard.TargetProperty="(UIElement.Visibility)"
                                                    Storyboard.TargetName="FocusEllipse">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ColorAnimation Duration="0" To="Black"
                                                    Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
                                                    Storyboard.TargetName="FocusEllipse" />
                                            <ColorAnimation Duration="0" To="White"
                                                    Storyboard.TargetProperty="(Shape.Stroke).(SolidColorBrush.Color)"
                                                    Storyboard.TargetName="path" />
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled" />
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                    <VisualState x:Name="Focused" />
                                    <VisualState x:Name="Unfocused" />
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Ellipse x:Name="FocusEllipse" Fill="#FFF13535" Visibility="Collapsed" />
                            <Path x:Name="path"
                                  Data="M0,0 L6,6 M6, 0 L0,6"
                                  Stroke="#FF898888"
                                  HorizontalAlignment="Center"
                                  VerticalAlignment="Center"
                                  StrokeThickness="1" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <DataTemplate x:Key="TabItemTemplate1">
            <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                <TextBlock Text="{Binding Header}" FontSize="16" />
                <telerik:RadButton Command="{Binding RemoveItemCommand}"
                        Style="{StaticResource CloseButton}"
                        Margin="10,0,0,0"
                        ToolTipService.ToolTip="Close" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="ContentTemplate">
            <UserControl Content="{Binding Content1}" />
        </DataTemplate>
        <Style TargetType="telerik:RadTabItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
 
        <telerik:RadTreeView Name="treeView" Grid.Column="0" Background="#FFD2E7FF"
                                    Width="200" AllowDrop="False" FontSize="12"
                                    SelectionChanged="treeView_SelectionChanged">
            <telerik:RadTreeViewItem Header="Group A" IsExpanded="True">
                <telerik:RadTreeViewItem Header="Page A-1" IsExpanded="False">
                </telerik:RadTreeViewItem>
                <telerik:RadTreeViewItem Header="Group B" IsExpanded="True">
                    <telerik:RadTreeViewItem Header="Page B-1" IsExpanded="False">
                    </telerik:RadTreeViewItem>
                    <telerik:RadTreeViewItem Header="Page B-2" IsExpanded="False">
                    </telerik:RadTreeViewItem>
                    <telerik:RadTreeViewItem Header="Page B-3" IsExpanded="False">
                    </telerik:RadTreeViewItem>
                    <telerik:RadTreeViewItem Header="Page B-4" IsExpanded="False">
                    </telerik:RadTreeViewItem>
                </telerik:RadTreeViewItem>
                <telerik:RadTreeViewItem Header="Group C" IsExpanded="True">
                    <telerik:RadTreeViewItem Header="Page C-1" IsExpanded="False">
                    </telerik:RadTreeViewItem>
                </telerik:RadTreeViewItem>
            </telerik:RadTreeViewItem>
        </telerik:RadTreeView>
 
        <telerik:RadTabControl Grid.Column="1" Name="tabMain" VerticalAlignment="Stretch"
                                            HorizontalAlignment="Stretch"
                                            DropDownDisplayMode="Collapsed" ScrollMode="Viewport"
                                            BorderThickness="0,1,0,0" Opacity="0.985" SelectedIndex="3"
                                            HeaderBackground="#62DED7C4" IsDropDownOpen="False" BorderBrush="#FF5D759C"
                                            FontWeight="Bold" ItemTemplate="{StaticResource TabItemTemplate1}"
                                            ItemsSource="{Binding Tabs}" ContentTemplate="{StaticResource ContentTemplate}" >
        </telerik:RadTabControl>
    </Grid>
</UserControl>

"MainPage.xaml.cs"
public partial class MainPage : UserControl
{
    private MainViewModel mainViewModel = new MainViewModel();
 
    public MainPage()
    {
        InitializeComponent();
 
        this.DataContext = mainViewModel;
    }
 
    private object GetPage(RadTreeViewItem argTabItem)
    {
        return new SilverlightControl1(argTabItem.Header.ToString());
    }
 
    private void treeView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
    {
        if (treeView != null && treeView.SelectedItem != null)
        {
            RadTreeViewItem treeitem = treeView.SelectedItem as RadTreeViewItem;
            if (!treeitem.IsExpanded)
            {
                if (!mainViewModel.Tabs.Any(c => c.Header.ToString() == treeitem.Header.ToString()))
                {
                    mainViewModel.AddItem(treeitem.Header.ToString(), GetPage(treeitem));
                }
            }
        }
    }
}

"MainViewModel.cs"
public class MainViewModel
{
    public MainViewModel()
    {
        this.Tabs = new ObservableCollection<TabViewModel>();
    }
 
    /// <summary>
    /// Gets the collection of tabs.
    /// </summary>
    public ObservableCollection<TabViewModel> Tabs
    {
        get;
        private set;
    }
 
    /// <summary>
    /// Adds new tab item to the Tabs collection.
    /// </summary>
    public void AddItem(string argHeader, object argContent)
    {
        TabViewModel newTabItem = new TabViewModel(this);
        newTabItem.Header = argHeader;
        newTabItem.IsSelected = true;
        newTabItem.Content1 = argContent;
        this.Tabs.Add(newTabItem);
        this.InvalidateCommands();
    }
 
    /// <summary>
    /// Removes an item from the Tabs collection.
    /// </summary>
    /// <param name="tabItem">The tab item.</param>
    public void RemoveItem(TabViewModel tabItem)
    {
        this.Tabs.Remove(tabItem);
        this.InvalidateCommands();
    }
 
    private void InvalidateCommands()
    {
        foreach (var tab in this.Tabs)
        {
            tab.RemoveItemCommand.InvalidateCanExecute();
        }
    }
}

"TabViewModel.cs"
public class TabViewModel
{
    private bool isSelected;
    private readonly MainViewModel mainViewModel;
 
    public TabViewModel(MainViewModel mainViewModel)
    {
        this.mainViewModel = mainViewModel;
 
        this.RemoveItemCommand = new DelegateCommand(
            delegate
            {
                this.mainViewModel.RemoveItem(this);
            },
            delegate
            {
                return true;
            });
    }
 
    public string Header
    {
        get;
        set;
    }
 
    public bool IsSelected
    {
        get
        {
            return this.isSelected;
        }
        set
        {
            if (this.isSelected != value)
            {
                this.isSelected = value;
                this.OnPropertyChanged("IsSelected");
            }
        }
    }
 
    public object Content1
    {
        get;
        set;
    }
 
    public DelegateCommand RemoveItemCommand { get; set; }
 
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
 
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

"SilverlightControl1.xaml"
<Grid x:Name="LayoutRoot" Background="White">
    <Button Name="btnText" FontSize="26"></Button>
</Grid>

"SilverlightControl1.xaml.cs"
public partial class SilverlightControl1 : UserControl
{
    public SilverlightControl1(string argText)
    {
        InitializeComponent();
        btnText.Content = argText;
    }
}


Thank you for the support.

1 Answer, 1 is accepted

Sort by
0
Accepted
Martin Ivanov
Telerik team
answered on 03 Apr 2014, 03:45 PM
Hello Linnet,

In order to fix this issue you can replace the UserControl in the ContentTemplate of the tab control with a ContentPresenter.

<DataTemplate x:Key="ContentTemplate">
    <ContentPresenter Content="{Binding Content1}" />
</DataTemplate>
Please give this approach a try and let me know if you need any further assistance.

Regards,
Martin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
Tags
TabControl
Asked by
linnet
Top achievements
Rank 1
Answers by
Martin Ivanov
Telerik team
Share this question
or