设置矩形宽度在列表c# WPF的项目
本文关键字:WPF 项目 列表 设置 | 更新日期: 2023-09-27 18:08:39
如何设置矩形的宽度,通过在c#中通过用户控件划分列表中的Items
的数量,使用WPF必须在代码后面,而不是使用Xaml:
public partial class UserControl1 : UserControl
{
private List<Color> colours;
private int Highest;
private int Lowest;
private int Median;
public int Width {get; set;}
private Data mydata;
public Data data
{
get
{
return mydata;
}
set
{
mydata = value;
BindData();
}
}
public UserControl1()
{
colours = new List<Color>() { Colors.Red, Colors.White, Colors.Blue};
InitializeComponent();
if (Width == 0)
{
Width = 300;
}
}
private void BindData()
{
//work out rectangle width
Highest = Convert.ToInt32(mydata.Values.Max());
Lowest = Convert.ToInt32(mydata.Values.Min());
Median = Convert.ToInt32(mydata.Values.Average());
foreach (double item in mydata.Values)
{
//create rectangle of width specified
SetWidth();
}
}
private void SetWidth()
{
//divide number of items in list by total to define Width
}
private Color GetColourFromValue(int totalNumber)
{
var numOfColours = colours.Count;
if (totalNumber >= numOfColours)
{
return colours[totalNumber % numOfColours];
}
return colours[totalNumber];
}
private Color GetGradeColour(byte itemNumber, byte totalNumberItems, Color ItemColour)
{
byte multipler = (byte)(200 / totalNumberItems);
byte a = (byte)((itemNumber + 1) * multipler);
return Color.FromArgb(a, ItemColour.R, ItemColour.G, ItemColour.B);
}
private Rectangle CreateRectangle(double Value, int Width, Color ItemColor)//double value, width)
{
//create rectangle
var rectangle = new Rectangle()
{
//Fill = new SolidColorBrush(ItemColor)
};
//give rectangle width
return rectangle;
}
}
如果你想要一组控件自动共享父UserControl
的水平空间,那么使用Grid
控件与列。这比手动计算宽度要容易得多。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0"/>
<Rectangle Grid.Column="1"/>
<Rectangle Grid.Column="2"/>
<Rectangle Grid.Column="3"/>
</Grid>
代码:var grid = new Grid
{
ColumnDefinitions =
{
new ColumnDefinition(),
new ColumnDefinition(),
new ColumnDefinition(),
new ColumnDefinition()
}
};
var rectangle1 = new Rectangle { Fill = Brushes.Blue };
rectangle1.SetValue(Grid.ColumnProperty, 0);
grid.Children.Add(rectangle1);
var rectangle2 = new Rectangle { Fill = Brushes.Red };
rectangle2.SetValue(Grid.ColumnProperty, 1);
grid.Children.Add(rectangle2);
var rectangle3 = new Rectangle { Fill = Brushes.Green };
rectangle3.SetValue(Grid.ColumnProperty, 2);
grid.Children.Add(rectangle3);
var rectangle4 = new Rectangle { Fill = Brushes.Yellow };
rectangle4.SetValue(Grid.ColumnProperty, 3);
grid.Children.Add(rectangle4);