Casting a TabItem to UserControl in WPF

微笑、不失礼 提交于 2020-01-02 14:03:43

问题


I have a Tab Control on my main screen. It has different tab items. For example:

<TabControl Name="mainTab"  Padding="0" Margin="70,80,350,49">
            <!--Left,Top,Right, Bottom-->
            <TabItem GotFocus="TabItem_Animals_GotFocus">
                <TabItem.Header>
                    Animals
                </TabItem.Header>
                <ContentControl Margin="10">
                    <Frame Name="animalFrame" Source="AnimalWorkSpaceView.xaml"></Frame>
                </ContentControl>
            </TabItem>
            <TabItem GotFocus="TabItem_Calfs_GotFocus">
                <TabItem.Header>
                    Calfs
                </TabItem.Header>
                <ContentControl Margin="10">
                    <Frame Name="calfFrame" Source="CalfWorkSpaceView.xaml"></Frame>
                </ContentControl>
            </TabItem>

and so on..

Here is design-time preview of tabs:

Every tab item control is inherited from WorkSpaceViewControl (an abstract class derived from UserControl)

As you can see there is a Refresh button to refresh the control (Reload it's datagrid members)

The code behind Refresh button is:

private void buttonRefresh_Click(object sender, RoutedEventArgs e)
        {
        //var x = mainTab.SelectedItem as TabItem;
        //MessageBox.Show(x.Header.ToString());//shows the header
        //var t = x.Content as TextBlock;
        //MessageBox.Show(t.Text);

        var ctrl = mainTab.SelectedItem as TabItem;

        var myCtrl1 = (WorkSpaceViewControl)ctrl;
        myCtrl1.Refresh();
}

Refresh() is a virtual method in WorkSpaceViewControl class and overridden in subsequent classes.

Whenever I call that code, it gives me error on casting. I have tried a lot of methods of casting: Implicit, explicit (as you can see some tries in commented code above as well).

Here is code of Explicit casting I tried to implement (but failed):

public static explicit operator WorkSpaceViewControl(TabItem v)
        {
            if (v.Content is WorkSpaceViewControl)
            {
                return v.Content as WorkSpaceViewControl;
            }
            else
            {
                throw new InvalidCastException();
            }
        }

It always throws me Invalid Cast by taking into else condition:

Can I cast it and How? Thanks for answering it.

UPDATE

The abstract class is:

public abstract class WorkSpaceViewControl : UserControl
{
    public WorkSpaceViewControl()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        //
    }

    #region Inheritance Methods (for sub classes
    public virtual void GetSelectedEntry()
    {

    }

    public virtual void Refresh()
    {

    }

    public static explicit operator WorkSpaceViewControl(TabItem v)
    {
        if (v.Content is WorkSpaceViewControl)
        {
            return v.Content as WorkSpaceViewControl;
        }
        else
        {
            throw new InvalidCastException();
        }
    }



    #endregion
}

回答1:


You have an interface:

interface IWorkSpaceViewControl
{
    void GetSelectedEntry();
    void Refresh();

    bool CanSave { get; }
    void Save();
}

And a userControl:

<UserControl x:Class="WpfApplication9.DemoUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Name="btnChangeCanSave" Click="btnChangeCanSave_Click">Change CanSave</Button>
    </Grid>
</UserControl>

Code Behind:

public partial class DemoUserControl : UserControl, IWorkSpaceViewControl
{
    private bool canSave;

    public DemoUserControl()
    {
        InitializeComponent();
    }

    public void GetSelectedEntry()
    {
        // Your implementation
    }

    public void Refresh()
    {
        // Your Implementation
        Debug.WriteLine("DemoUserControl Refresh() executed");
    }


    public bool CanSave
    {
        get { return canSave; }
    }

    private void btnChangeCanSave_Click(object sender, RoutedEventArgs e)
    {
        canSave = !canSave;
    }


    public void Save()
    {
        Debug.WriteLine("DemoUserControl Save() executed");
    }
}

and a MainWindow:

<Window xmlns:WpfApplication9="clr-namespace:WpfApplication9"  x:Class="WpfApplication9.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCommand_CanExecute" Executed="SaveCommand_Executed"/>
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <WrapPanel>
            <Button Name="btnRefresh" Click="btnRefresh_Click">Refresh</Button>
            <Button Command="ApplicationCommands.Save">Save</Button>
        </WrapPanel>
        <TabControl Name="tabControl" Grid.Row="1">
            <TabItem>
                <TabItem.Header>Animals</TabItem.Header>
                <WpfApplication9:DemoUserControl Margin="10" />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

with Code Behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    private void btnRefresh_Click(object sender, RoutedEventArgs e)
    {
        IWorkSpaceViewControl control = tabControl.SelectedContent as IWorkSpaceViewControl;
        control.Refresh();
    }

    private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        if (tabControl != null)
        {
            e.CanExecute = ((IWorkSpaceViewControl)tabControl.SelectedContent).CanSave;
        }
    }

    private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        ((IWorkSpaceViewControl)tabControl.SelectedContent).Save();
    }
}



回答2:


Try this

if (v.GetType().BaseType == typeof(WorkSpaceViewControl))
{
    return v as WorkSpaceViewControl;
}


来源:https://stackoverflow.com/questions/28977705/casting-a-tabitem-to-usercontrol-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!