MVVM,TabControl,引用相同的内容

时间:2013-02-24 19:05:59

标签: wpf mvvm tabcontrol

我正在使用MVVM构建一个WPF应用程序,它包含一组tabcontrols,我在XMAL文件中引用了我的tabItemViewModel的observableCollection ...问题是我的所有tabitems包含相同的东西! (我的标签每个都包含一个文本框,如果我在一个标签中更改了我的文本框的内容,我在所有其他标签中看到相同的内容!如果我创建一个新标签,我编辑的所有内容都会消失! ),就像我的所有标签都与相同的视图模型或类似的东西相关!

我正在使用Josh Smith样本继续进行,我确信我遵循了相同的理念和架构!!!!

有任何帮助吗? 谢谢:) :))


my static ressources :

        <ResourceDictionary
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:view="clr-namespace:DealSaverMargo"
          xmlns:modelView="clr-namespace:ViewModelDealSaver;assembly=ViewModelDealSaver"
          >

            <DataTemplate DataType="{x:Type modelView:ClientCreationViewModel}">
                <view:ClientCreation />
            </DataTemplate>

            <DataTemplate DataType="{x:Type modelView:TabItemClientsListingModelView}">
                <view:ClientListing />
            </DataTemplate> (........)

            <DataTemplate x:Key="ClosableTabItemTemplate">
                <DockPanel >
                    <Button
                  Command="{Binding Path=CloseCommand}"
                Content="X"
                Cursor="Hand"
                DockPanel.Dock="Right"
                Focusable="False"
                FontFamily="Courier"
                FontSize="9"
                FontWeight="Bold"
                Margin="0,1,0,0"
                Padding="0"
                VerticalContentAlignment="Bottom"
                Width="16" Height="16"
                />
                    <ContentPresenter Content="{Binding Path=Header}"
                VerticalAlignment="Center">
                    </ContentPresenter>
                </DockPanel>
            </DataTemplate>

            <DataTemplate x:Key="TabsTemplate">
                <TabControl
              IsSynchronizedWithCurrentItem="True"
              ItemsSource="{Binding}"
              ItemTemplate="{StaticResource ClosableTabItemTemplate}"
              Margin="4"
              />
            </DataTemplate>




    </ResourceDictionary>

My MainWindowViewModel : 




public class MainWindowViewModel : ViewModelBase
{
    //Propriétés
    ObservableCollection<TabViewModel> _tabItems;

   //Propriétés publiques: 
    public ObservableCollection<TabViewModel> Workspaces
    {
        get
        {
            if (_tabItems == null)
            {
                _tabItems = new ObservableCollection<TabViewModel>();
                _tabItems.CollectionChanged += this.OnWorkspacesChanged;
            }
            return _tabItems;
        }
    }

    void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null && e.NewItems.Count != 0)
            foreach (TabViewModel workspace in e.NewItems)
                workspace.RequestClose += this.OnWorkspaceRequestClose;

        if (e.OldItems != null && e.OldItems.Count != 0)
            foreach (TabViewModel workspace in e.OldItems)
                workspace.RequestClose -= this.OnWorkspaceRequestClose;
    }
    void OnWorkspaceRequestClose(object sender, EventArgs e)
    {
        TabViewModel workspace = sender as TabViewModel;
        workspace.Dispose();
        this.Workspaces.Remove(workspace);
    }
    public MainWindowViewModel()
    {
        _tabItems = new ObservableCollection<TabViewModel>();
        //Assignation des commandes: 
        _clientCreationCommand = new RelayCommand(new Action<object>(ClientCreationTabCommand));
        _dealCreationCommand = new RelayCommand(new Action<object>(DealCreationTabCommand));
        _clientsManagementCommand = new RelayCommand(new Action<object>(ClientListingTabcommand));
    }
    #region //Commandes :

    public ICommand _clientCreationCommand
    {
        get;
        set;
    }

    public ICommand _dealCreationCommand
    {
        get;
        set;
    }

    public ICommand _clientsManagementCommand
    {
        get;
        set;
    }

    #endregion
    #region //Gestion des commandes :
    /// <summary>
    /// Rajout des workspaces :
    /// </summary>
    /// <param name="param"></param>
    public void ClientCreationTabCommand(object param)
    {
        TabViewModel clientsManager = new ClientCreationViewModel("Client Creation");
        _tabItems.Add(clientsManager);
        ICollectionView collection = CollectionViewSource.GetDefaultView(_tabItems);
        collection.MoveCurrentTo(clientsManager); //the corresponding view is set to active. 

    }

    public void ClientListingTabcommand(object param)
    {
        TabViewModel clientsListing = new TabItemClientsListingModelView("Client Management");
        _tabItems.Add(clientsListing);
        ICollectionView collection = CollectionViewSource.GetDefaultView(_tabItems);
        collection.MoveCurrentTo(clientsListing); //the corresponding view is set to active. 
    }
    #endregion


}


my Client Creation user control : 



     <UserControl x:Class="DealSaverMargo.ClientCreation"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

                xmlns:view="clr-namespace:DealSaverMargo.Views">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="6*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>
                <Label Content="Deals Database" Grid.Row="0" FontSize="20" FontWeight="Bold" Background="#FFBFBFBF"></Label>

                <Grid Grid.Row="1" VerticalAlignment="Center">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <!--Définition des elements-->
                    <Label Content="ID" HorizontalAlignment="Left" Width="90" />
                    <TextBox x:Name="ID" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch" Margin="3"></TextBox>
                    <Label Grid.Row="1" Content="Social Identity" HorizontalAlignment="Left" Width="90" />
                    <TextBox x:Name="socialIdentityBox" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch" Margin="3"></TextBox>
                    <Label Grid.Column="0" Grid.Row="2" Content="Phone Number"/>
                    <TextBox x:Name="phoneNumberBox" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" Margin="3"></TextBox>
                    <Label Grid.Column="0" Grid.Row="3" Content="Mail Address"/>
                    <TextBox x:Name="mailAddressBox" Grid.Column="1" Grid.Row="3" HorizontalAlignment="Stretch" Margin="3"></TextBox>
                    <Label Grid.Column="0" Grid.Row="4" Content="Created By"/>
                    <TextBox x:Name="createdByBox" Grid.Column="1" Grid.Row="4" HorizontalAlignment="Stretch" Margin="3"></TextBox>
                </Grid>
                <Grid Grid.Row="2">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="2*"></ColumnDefinition>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <Button Grid.Column="1" Margin="5" Content="Add"></Button>
                        <Button Grid.Column="2" Margin="5" Content="Cancel"></Button>
                    </Grid>
                </Grid>
            </Grid>
        </UserControl>

My client creation viewmodel :




        public class ClientCreationViewModel : TabViewModel
            {
                public ClientCreationViewModel(string header)
                    : base(header)
                {
                }
                private string _socialIdentity;
                public string SocialIdentity
                {
                    get
                    {
                        return this._socialIdentity;
                    }
                    set
                    {
                        if (_socialIdentity != value)
                        {
                            _socialIdentity = value;
                            OnPropertyChanged("SocialIdentity");
                        }
                    }
                }

                private string _phone;
                public string Phone
                {
                    get
                    {
                        return _phone;
                    }
                    set
                    {
                        if (value != _phone)
                        {
                            _phone = value;
                            OnPropertyChanged("Phone");
                        }
                    }
                }

                private string _mail;
                public string Mail
                {
                    get
                    {
                        return _mail;
                    }
                    set
                    {
                        _mail = value;
                        OnPropertyChanged("Mail");
                    }
                }

                private string _createdBy;
                public string CreatedBy
                {
                    get
                    {
                        return _createdBy;
                    }
                    set
                    {
                        if (value != _createdBy)
                        {
                            OnPropertyChanged("CreatedBy");
                        }
                    }
                }
            }


    and my tabviewmodel ( from which all my tabitems inherits)


            public class TabViewModel : ViewModelBase
            {

                //Fields : 
                RelayCommand _closeCommand;


                //Constructor:
                public TabViewModel(string header)
                {
                    this.Header = header;
                }


                #region CloseCommand

                /// <summary>
                /// Returns the command that, when invoked, attempts
                /// to remove this workspace from the user interface.
                /// </summary>
                public ICommand CloseCommand
                {
                    get
                    {
                        if (_closeCommand == null)
                            _closeCommand = new RelayCommand(param => this.OnRequestClose());

                        return _closeCommand;
                    }
                }

                #endregion // CloseCommand

                #region RequestClose [event]

                /// <summary>
                /// Raised when this workspace should be removed from the UI.
                /// </summary>
                public event EventHandler RequestClose;

                void OnRequestClose()
                {
                    EventHandler handler = this.RequestClose;
                    if (handler != null)
                        handler(this, EventArgs.Empty);
                }

                #endregion // RequestClose [event]

                public String Header { get; set; }


            }


The viewmodelbase is the classic modelbase which can be found everywhere in internet :D

Thanks !!!!

@大卫 这是我的主窗口XXAML

<Window.DataContext>
        <!-- Declaratively create an instance of our MainWindowVie -->
        <modelView:MainWindowViewModel></modelView:MainWindowViewModel>
    </Window.DataContext>

    <Window.Resources>
        <ResourceDictionary Source="MainWindowRessources.xaml"/>  
    </Window.Resources>
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="_Application" >
                <MenuItem Header="_Deal Creation" Command="{Binding Path=_dealCreationCommand}"/>
                <MenuItem Header="_Client Creation" Command="{Binding Path=_clientCreationCommand}" />

                <MenuItem Header="Clients _Managment" Command="{Binding Path=_clientsManagementCommand}"/>
                <MenuItem Header="_Sectors Management"/>
                <MenuItem Header="S_tatistics"/>
                <Separator></Separator>
                <MenuItem Header="_Exit"/>
            </MenuItem>

            <MenuItem Header="Help">
                <MenuItem Header="Help"/>
                <MenuItem Header="Deal Saver"/>
            </MenuItem>
        </Menu>


        <ContentControl Content="{Binding Path=Workspaces}" ContentTemplate="{StaticResource TabsTemplate}" >

        </ContentControl>
    </DockPanel>

1 个答案:

答案 0 :(得分:0)

您似乎缺少ClientCreation用户控件中文本框的Text属性的数据绑定。

例如:

<TextBox x:Name="socialIdentityBox" Text="{Binding SocialIdentity, Mode=TwoWay}" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch" Margin="3" />

尝试设置这些并查看会发生什么。