[英]Add Tab Dynamically Into A tabControl based on Selected item from ListBox
I am working on MVVM sample app. 我正在开发MVVM示例应用程序。 I have 2 projects inside my solution in VSC# 2010. In one project (main project) I have a mainwindow.xaml which has two grids, one located on right side and other on the left.
在VSC#2010的解决方案中,我有2个项目。在一个项目(主项目)中,我有一个mainwindow.xaml,它具有两个网格,一个位于右侧,另一个位于左侧。 Left side grid has a listBox which has items with the help of observablecollection<>.
左侧网格具有一个listBox,其中的listBox带有observablecollection <>的帮助。 Eg Voltage, I2C etc are the items.
例如,电压,I2C等。 I have also set the
selecteditem
property for the listbox which gives me the selecteditem
. 我还为列表框设置了
selecteditem
属性,这为我提供了selecteditem
。
My main query is the grid towards the right side which has a TABCONTROL with one item("CONNECT") added by default. 我的主要查询是右侧的网格,该网格具有TABCONTROL,默认情况下添加了一项(“ CONNECT”)。 What I need is to add the tabitem (egVoltage tab) inside the tabcontrol when I select the "Voltage" item from listBox.
我需要的是在从listBox中选择“电压”项时在tab控件中添加tabitem(例如“电压”选项卡)。
TabControl and ListBox inside my grid: 我的网格中的TabControl和ListBox:
<Grid Grid.Column="0" Name="BoardTabSelect" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBox Name="ButtonPanel" Style="{DynamicResource styleBanner}" ItemsSource="{Binding BoardTabs, Mode=TwoWay}" SelectedItem="{Binding SelectedTab, Mode=TwoWay}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="BoardtabChanger" Margin="53,27,0,0" Text="{Binding TabOperation}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
My tabcontrol: 我的tabcontrol:
<Grid Grid.Row="0" >
<TabControl Name="ConnectTab" Style="{DynamicResource styleBackground}">
<tablocal:CloseableTabItem Header="Connect" x:Name="ConnectMain" MouseDoubleClick="TabItem_MouseDoubleClick">
<DockPanel>
<ListView Name="listView" Height="460" Margin="0,-77,0,0" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct, Mode=TwoWay}">
<ListView.View>
<GridView>
<GridViewColumn Width="300" Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Width="283" Header="Connection Status" DisplayMemberBinding="{Binding Connection_Status}" />
</GridView>
</ListView.View>
</ListView>
<Button Content="Connect" Height="23" HorizontalAlignment="Stretch" Margin="-920,500,0,0" Name="ConnectBtnGrid" VerticalAlignment="Stretch" Width="100" Command="{Binding Path=ConnectCommand}" />
<Button Content="Update MSP430" Height="23" HorizontalAlignment="Stretch" Margin="-560,500,0,0" Name="UpdateMSPBtn" VerticalAlignment="Stretch" Width="100" />
<Button Content="Disconnect" Height="23" HorizontalAlignment="Stretch" Margin="-220,500,0,0" Name="DisconnectBtn" VerticalAlignment="Stretch" Width="100" Command="{Binding Path=DisconnectCommand}" />
</DockPanel>
</tablocal:CloseableTabItem>
</TabControl>
</Grid>
My ViewModel class is here: 我的ViewModel类在这里:
public List<Product> m_Products;
public ObservableCollection<Product> m_BoardTabs;
public ProductViewModel()
{
m_Products = new List<Product>()
{
new Product() {Name = "Bavaria", Connection_Status = "Disconnected"},
new Product() {Name = "Redhook", Connection_Status = "Disconnected"},
};
m_BoardTabs = new ObservableCollection<Product>()
{
new Product() {TabOperation = "Connect"}
};
}
public List<Product> Products
{
get
{
return m_Products;
}
set
{
m_Products = value;
}
}
public ObservableCollection<Product> BoardTabs
{
get
{
return m_BoardTabs;
}
set
{
m_BoardTabs = value;
}
}
/// <summary>
/// get:
/// set:
/// </summary>
private Product m_SelectedItem;
public Product SelectedProduct
{
get
{
return m_SelectedItem;
}
set
{
m_SelectedItem = value;
NotifyPropertyChanged("SelectedProduct");
}
}
private Product m_SelectedTab;
public Product SelectedTab
{
get
{
return m_SelectedTab;
}
set
{
m_SelectedTab = value;
NotifyPropertyChanged("SelectedTab");
onTabChanged();
}
}
void onTabChanged()
{
if (SelectedTab.TabOperation == "Voltage")
{
//Add tab here
}
}
public Product value { get; set; }
/// <summary>
/// get:
/// set:
/// </summary>
private ICommand mUpdater;
public ICommand ConnectCommand
{
get
{
if (mUpdater == null)
mUpdater = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));
return mUpdater;
}
set
{
mUpdater = value;
}
}
public bool SaveCanExecute()
{
return true;
}
public void SaveExecuted()
{
if (SelectedProduct.Connection_Status == "Disconnected" && SelectedProduct.Name == "Bavaria")
{
SelectedProduct.Connection_Status = "Connected";
m_BoardTabs.Add(new Product() { TabOperation = "I2C" });
m_BoardTabs.Add(new Product() { TabOperation = "Voltage" });
m_BoardTabs.Add(new Product() { TabOperation = "Clock" });
m_BoardTabs.Add(new Product() { TabOperation = "Codec" });
m_BoardTabs.Add(new Product() { TabOperation = "EEPROM" });
}
else if (SelectedProduct.Connection_Status == "Disconnected" && SelectedProduct.Name == "Redhook")
{
SelectedProduct.Connection_Status = "Connected";
m_BoardTabs.Add(new Product() { TabOperation = "I2C" });
m_BoardTabs.Add(new Product() { TabOperation = "Voltage" });
m_BoardTabs.Add(new Product() { TabOperation = "Clock" });
m_BoardTabs.Add(new Product() { TabOperation = "Codec" });
m_BoardTabs.Add(new Product() { TabOperation = "EEPROM" });
m_BoardTabs.Add(new Product() { TabOperation = "PCM Route" });
m_BoardTabs.Add(new Product() { TabOperation = "PCM Route #" });
m_BoardTabs.Add(new Product() { TabOperation = "PCM Gen" });
m_BoardTabs.Add(new Product() { TabOperation = "SD Card" });
m_BoardTabs.Add(new Product() { TabOperation = "FPGA" });
m_BoardTabs.Add(new Product() { TabOperation = "PCMPDM" });
m_BoardTabs.Add(new Product() { TabOperation = "Data Gen" });
}
}
Mind you the tabitem "VOLTAGE" which I want to add in my control is part of another project which I mentioned in the beginning. 请注意,我要添加到控件中的Tabltite“ VOLTAGE”是我一开始提到的另一个项目的一部分。 It has its own view, viewmodel and model class.
它具有自己的视图,视图模型和模型类。 The following is the view in.xaml file which I want to add:
以下是我要添加的in.xaml视图文件:
<Grid Name="VoltageTab" Height="572" Width="590" DataContext="{StaticResource VoltageViewModel}" >
// Some UI componments which shud be placed inside VOLTAGE Tab on selecting Voltage from ListBox.
</Grid>
As you can see above, I want the above view to be placed inside the VoltageTab which should get created once user clicks Voltage item from ListBox. 从上面可以看到,我希望将上面的视图放置在VoltageTab内,一旦用户单击ListBox中的Voltage项,就应该创建该视图。
TabControl has an ItemsSource property.. this can be bound to an observable collection of objects from the ViewModel. TabControl具有ItemsSource属性。此属性可以绑定到ViewModel中可观察到的对象集合。
Along with this, the object being used in the observable collection must have an associated DataTemplate which should be a TabItem. 与此同时,可观察集合中使用的对象必须具有关联的DataTemplate,它应该是TabItem。
As a result, when you add an object to the ObservableCollection which acts as a source to your TabControl using the DataTemplate a new TabItem gets added to the TabControl. 如此一来,当您使用DataTemplate将对象添加到ObservableCollection用作TabControl的源时,新的TabItem将添加到TabControl。
Also make sure you have one entry / object in the observablecollection for the initial tabitem. 还要确保您在observablecollection中有一个用于初始表项的条目/对象。
You can refer to the TabItem from the other project in the DataTemplate by adding appropriate namespace / references 您可以通过添加适当的名称空间/引用来引用DataTemplate中其他项目中的TabItem
Here is the ViewModel class 这是ViewModel类
public class TabItemDetail
{
public string Header { get; set; }
}
public class MainWindowViewModel : INotifyPropertyChanged
{
#region Members
List<string> _dataSource = null;
string _selectedDataSource = null;
ObservableCollection<TabItemDetail> _tabItems = null;
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
public ObservableCollection<TabItemDetail> Items
{
get
{
if (_tabItems == null)
{
_tabItems = GetTabItems();
}
return _tabItems;
}
}
public List<string> DataSource
{
get
{
if (_dataSource == null)
{
_dataSource = GetDataSource();
}
return _dataSource;
}
}
public string SelectedDataSource
{
get { return _selectedDataSource; }
set
{
if (_selectedDataSource == value)
return;
_selectedDataSource = value;
AddItemsToTab(value);
OnPropertyChanged("SelectedDataSource");
}
}
#region Private methods
private void AddItemsToTab(string selectedItem)
{
if (_tabItems != null && _tabItems.Count > 0)
{
var query = from item in _tabItems
where item.Header == selectedItem
select item;
if (query.Count() == 1)
return;
else
_tabItems.Add(new TabItemDetail { Header = selectedItem });
}
}
private List<string> GetDataSource()
{
List<string> source = new List<string>();
source.Add("Default tab");
source.Add("Voltage Tab");
return source;
}
private ObservableCollection<TabItemDetail> GetTabItems()
{
ObservableCollection<TabItemDetail> newSource = new ObservableCollection<TabItemDetail>();
newSource.Add(new TabItemDetail { Header = "Connect" });
return newSource;
}
#endregion
}
here is the View 这是视图
<Window x:Class="SampleApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApp"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:TabItemDetail}">
<TabItem Header="{Binding Header}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding DataSource}" SelectedItem="{Binding SelectedDataSource}"/>
<TabControl Grid.Column="2" local:MySampleAttachedProperty.Header="{Binding SelectedDataSource}">
<TabItem Header ="Connect" />
</TabControl>
</Grid>
here is the new attached property class which does the trick 这是新的附加属性类
public class MySampleAttachedProperty
{
public static string GetHeader(DependencyObject obj)
{
return (string)obj.GetValue(HeaderProperty);
}
public static void SetHeader(DependencyObject obj, string value)
{
obj.SetValue(HeaderProperty, value);
}
// Using a DependencyProperty as the backing store for Header. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.RegisterAttached("Header", typeof(string), typeof(MySampleAttachedProperty), new UIPropertyMetadata(CallBack));
private static void CallBack(object sender, DependencyPropertyChangedEventArgs args)
{
TabControl tabControl = sender as TabControl;
TabItem newTab = new TabItem { Header = args.NewValue };
tabControl.Items.Add(newTab);
newTab.Focus();
}
}
The data template for the tabcontrol should not contain a tabitem. tabcontrol的数据模板不应包含tabitem。 The tabcontrol is generating a tabitem for each element in the bound Collection.
tabcontrol为绑定的Collection中的每个元素生成一个tabitem。 To enable databinding to the tabitem header set the itemcontainerstyle property of the tabcontrol.
要启用到tabitem标头的数据绑定,请设置tabcontrol的itemcontainerstyle属性。 Here is a small sample:
这是一个小样本:
The View: 风景:
<Window x:Class="WpfLab.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">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
<TabControl ItemsSource="{Binding ProductTabs}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
<ListBox Grid.Column="1" ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct}"/>
</Grid>
The ViewModel ViewModel
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
namespace WpfLab
{
public partial class MainWindow : Window
{
Product selectProduct;
public MainWindow()
{
InitializeComponent();
Products = new ObservableCollection<Product>();
ProductTabs = new ObservableCollection<Product>();
var products = Enumerable.Range(0, 10).Select(i => new Product { Header = "Product " + i });
foreach (var p in products)
Products.Add(p);
DataContext = this;
}
public Product SelectedProduct
{
get { return this.selectProduct; }
set
{
UpdateTabs(this.selectProduct, value);
this.selectProduct = value;
}
}
public ObservableCollection<Product> Products { get; private set; }
public ObservableCollection<Product> ProductTabs { get; private set; }
void UpdateTabs(Product old, Product @new)
{
if (ProductTabs.Any(p => p == old))
ProductTabs.Remove(old);
ProductTabs.Add(@new);
}
}
public class Product
{
public string Header { get; set; }
public override string ToString()
{
return Header;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.