デザイン画面
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace _20190329_ListBoxのDataTemplateをコードで
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<int> myData = new List<int>() { 12, 345, 6789, 0 };
DataContext = myData;
MyListBox.ItemTemplate = CreateDataTemplate();
}
private DataTemplate CreateDataTemplate()
{
ImageBrush myPattern = MakeTileBrush(MakeCheckeredPattern(10, Colors.LightGray));
var eBorder = new FrameworkElementFactory(typeof(Border));
eBorder.SetValue(Border.BackgroundProperty, myPattern);
eBorder.SetValue(WidthProperty, 100.0);
eBorder.SetValue(HeightProperty, 20.0);
var eTextBlock = new FrameworkElementFactory(typeof(TextBlock));
eTextBlock.SetBinding(TextBlock.TextProperty, new Binding());
var eStackPanel = new FrameworkElementFactory(typeof(StackPanel));
eStackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
eStackPanel.AppendChild(eBorder);
eStackPanel.AppendChild(eTextBlock);
var dt = new DataTemplate();
dt.VisualTree = eStackPanel;
return dt;
}
<summary>
</summary>
<param name="cellSize"></param>
<param name="gray"></param>
<returns></returns>
private WriteableBitmap MakeCheckeredPattern(int cellSize, Color gray)
{
int width = cellSize * 2;
int height = cellSize * 2;
var wb = new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
int stride = wb.Format.BitsPerPixel / 8 * width;
byte[] pixels = new byte[stride * height];
int p = 0;
Color iro;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if ((y < cellSize & x < cellSize) | (y >= cellSize & x >= cellSize))
{
iro = Colors.White;
}
else { iro = gray; }
p = y * stride + x * 3;
pixels[p] = iro.R;
pixels[p + 1] = iro.G;
pixels[p + 2] = iro.B;
}
}
wb.WritePixels(new Int32Rect(0, 0, width, height), pixels, stride, 0);
return wb;
}
<summary>
</summary>
<param name="bitmap"></param>
<returns></returns>
private ImageBrush MakeTileBrush(BitmapSource bitmap)
{
var imgBrush = new ImageBrush(bitmap);
imgBrush.Stretch = Stretch.Uniform;
imgBrush.TileMode = TileMode.Tile;
imgBrush.Viewport = new Rect(0, 0, bitmap.Width, bitmap.Height);
imgBrush.ViewportUnits = BrushMappingMode.Absolute;
return imgBrush;
}
}
}
58行目以降は前回の
からコピペ
ListBoxの要素の見た目変更でItemTemplateのDataTemplate
これをコードで書くと
こう、長くなる
違うのはBorderのBackground
WriteableBitmapで作った
市松模様のImageBrushにしているところ、37行目
ホントはこれが
XAMLでできればよかったんだけど、わからなかったのでコードで書くことになった
DataTemplate
- 要素の作成はFrameworkElementFactoryにtypeofで種類を指定
- プロパティの指定はSetValue
- Panel要素の中に入れるときはAppendChild
参照したところ
ギットハブ
関連記事
前回、2019/03/29は昨日
2019/03/30は同日
2016/5/21は3年前