选项卡项目的数量不是预先确定的。我只想创建新的选项卡项,然后在当前项中添加新的矩形。
我正在生成新的选项卡项目(下面是代码),但是如何在当前选项卡中添加矩形?
var _FloorName = (from fn in db.floors select fn.floorname).ToList();
if (_FloorName.Count > 0)
{
for (int i = 0; i < _FloorName.Count; i++)
{
tabControl1.Items.Add(_FloorName[i]);
}
}
最佳答案
这是您可以采取的一种方法:
Grid
(或其他容器)到每个 TabItem
创建它们时Rectangle
, 用你想要的画笔/尺寸tabControl1.SelectedContent
, 将其转换为 Grid
(或您的容器类型)grid.Children.Add(rectangle)
这是一个完整的代码示例(使用丰富的代码隐藏)。
MainWindow.xaml:
<Window x:Class="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">
<StackPanel Margin="12">
<TabControl Name="tabControl1" Height="250" />
<Button Content="Add Rectangle" Click="Button_Click"
Width="90" Height="25" Margin="5" />
</StackPanel>
</Window>
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
public class Floor
{
public Floor(string name = null)
{
this.Name = name;
}
public string Name { get; set; }
}
public class FakeDb
{
public IEnumerable<Floor> Floors
{
get
{
return new List<Floor>()
{
new Floor("floor1"),
new Floor("floor2"),
new Floor("floor3"),
};
}
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeTabControl();
}
private void InitializeTabControl()
{
var db = new FakeDb();
var floorNames = (from fn in db.Floors select fn.Name).ToList();
foreach (string floorName in floorNames)
{
var item = new TabItem()
{
Header = floorName,
Content = new Grid(),
};
tabControl1.Items.Add(item);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var random = new Random();
var rectangle = new Rectangle()
{
Stroke = Brushes.Black,
Fill = Brushes.SkyBlue,
Width = 50,
Height = 75,
Margin = new Thickness(
left: random.NextDouble() * 300,
top: random.NextDouble() * 150,
right: 0,
bottom: 0),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
};
var grid = (Grid)tabControl1.SelectedContent;
grid.Children.Add(rectangle);
}
}
关于c# - WPF如何创建选项卡项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6759167/