作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个网格,
<Grid>
<TabControl Name="mainTabControl" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ObservableCollectionTabItems}" Background="White" Margin="10,0,0,0">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}" >
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Close" Click="MenuItemCloseTab_Click">
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</Grid>
<Grid Background="#FFD61B1B">
<ListBox x:Name="RightListBox" SelectionMode="Single" SelectionChanged="RightListBox_OnSelectionChanged" IsSynchronizedWithCurrentItem="true" Margin="10,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Margin="10" Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
this._vmMainWindowTabControl.AddTab("ViewOne", "Test");
public class VMMainWindowTabControl :VMBase
{
private VMParentForViews vmParentForViews;
public VMMainWindowTabControl()
{
ObservableCollectionTabItems = new ObservableCollection<VMParentForViews>();
}
public ObservableCollection<VMParentForViews> ObservableCollectionTabItems { get; set; }
///<summary>
/// I'm trying to get controls to Tabitem with SelectedIndex but I have not success.
/// </summary>
//public int SelectedIndex
//{
// get
// {
// ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.ObservableCollectionTabItems);
// return collectionView.CurrentPosition;
// }
// set
// {
// ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.ObservableCollectionTabItems);
// collectionView.MoveCurrentToPosition(value);
// OnPropertyChanged("SelectedIndex");
// }
//}
/// <summary>
/// Adds the tab to the TabControl
/// </summary>
/// <param name="viewType">Type of the view.</param>
/// <param name="header">Header of the TabItem.</param>
public void AddTab(string viewType, string header)
{
if(viewType.Equals("ViewOne"))
{
vmParentForViews = new VMViewTypeOne(header);
this.ObservableCollectionTabItems.Add(vmParentForViews);
}
// Set the new tab to be the current tab
ICollectionView collectionView1 = CollectionViewSource.GetDefaultView(this.ObservableCollectionTabItems);
if (collectionView1 != null)
{
collectionView1.MoveCurrentTo(vmParentForViews);
}
}
/// <summary>
/// Closes the tab item.
/// </summary>
public void CloseTabItem(Object sender)
{
VMParentForViews vmParentForViews = (sender as MenuItem).DataContext as VMParentForViews;
this.ObservableCollectionTabItems.Remove(vmParentForViews);
}
public void AddElement(Object sender)
{
// How I can do this.
}
}
最佳答案
我相信你的 MVVM 越来越模糊,你可以通过绑定(bind)做更多的事情。
我已经整理了一个我认为你所追求的例子,使用绑定(bind)、模板和 RoutedCommands 来实现你所说的你所追求的功能。
它像这样工作......
我的示例中有 3 个模型,MyModel1 到 MyModel3,它们基本上都是
public class MyModel1
{
public string Header { get { return "One"; }}
}
public MyViewModel()
{
this.AvailableItems = new Collection<Type>() { typeof(MyModel1), typeof(MyModel2), typeof(MyModel3) };
this.Items = new ObservableCollection<object>();
}
public Collection<Type> AvailableItems { get; set; }
public ObservableCollection<object> Items { get; set; }
public void AddItem(Type type)
{
var item = Items.FirstOrDefault(i => i.GetType() == type);
if (item == null)
{
item = Activator.CreateInstance(type);
Items.Add(item);
}
SelectedItem = item;
}
internal void RemoveItem(object item)
{
var itemIndex = this.Items.IndexOf(item);
if (itemIndex > 0)
{
SelectedItem = Items[itemIndex - 1];
}
else if (Items.Count > 1)
{
SelectedItem = Items[itemIndex + 1];
}
Items.Remove(item);
}
public object SelectedItem
{
get { return selectedItem; }
set
{
if (value != selectedItem)
{
selectedItem = value;
OnPropertyChanged();
}
}
}
private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
<UserControl x:Class="StackOverflow._20933056.UserControl1" 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">
<TextBlock Text="User Control 1" />
</UserControl>
public partial class MainWindow : Window
{
public static RoutedCommand CloseItemCommand = new RoutedCommand("CloseItem", typeof(MainWindow));
public MainWindow()
{
this.ViewModel = new MyViewModel();
InitializeComponent();
}
public MyViewModel ViewModel { get; set; }
private void MyListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.ViewModel.AddItem(e.AddedItems.OfType<Type>().FirstOrDefault());
}
private void CommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}
private void CommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
this.ViewModel.RemoveItem(e.Parameter);
}
<Window x:Class="StackOverflow._20933056.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:this="clr-namespace:StackOverflow._20933056"
DataContext="{Binding RelativeSource={RelativeSource Self}, Path=ViewModel}"
Title="MainWindow" Height="600" Width="800">
<Window.Resources>
<ContextMenu x:Key="TabContextMenu">
<MenuItem Header="Close" Command="{x:Static this:MainWindow.CloseItemCommand}" CommandParameter="{Binding}" />
</ContextMenu>
<DataTemplate DataType="{x:Type this:MyModel1}">
<this:UserControl1 DataContext="{Binding}" ContextMenu="{StaticResource TabContextMenu}" />
</DataTemplate>
<DataTemplate DataType="{x:Type this:MyModel2}">
<this:UserControl2 DataContext="{Binding}" ContextMenu="{StaticResource TabContextMenu}" />
</DataTemplate>
<DataTemplate DataType="{x:Type this:MyModel3}">
<this:UserControl2 DataContext="{Binding}" ContextMenu="{StaticResource TabContextMenu}" />
</DataTemplate>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding Path=Header}" />
<Setter Property="ContextMenu" Value="{StaticResource TabContextMenu}" />
</Style>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{x:Static this:MainWindow.CloseItemCommand}" CanExecute="CommandBinding_OnCanExecute" Executed="CommandBinding_OnExecuted" />
</Window.CommandBindings>
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox x:Name="MyListBox" ItemsSource="{Binding Path=AvailableItems}" SelectionChanged="MyListBox_OnSelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type system:Type}"><TextBlock Text="{Binding Path=Name}" /></DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TabControl Grid.Column="1" ItemsSource="{Binding Path=Items}" SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" />
</Grid>
</Grid>
</Window>
关于c# - 如何从自定义列表框中将按钮、TexBlocks 等添加到 Dynamic ObservableCollection Tabitem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933056/
我是一名优秀的程序员,十分优秀!