【发布时间】:2017-04-05 02:49:25
【问题描述】:
可以在数据模板中使用网格来格式化以对齐数据模板的元素吗?
我对 wpf 非常陌生,我正在尝试使用数据模板来格式化列表框的显示。我在数据模板中定义了一个网格,但我定义的文本块似乎没有放在我期望的列中。
我定义了一个 3 列 1 行的网格,并计划将每个元素放在每个相应的列中,但我得到的结果如下所示:
我希望在我指定的列中看到元素正确对齐。我做错了什么?
我已附上我的 xaml 以供说明
<Window x:Class="TestWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestWPF"
mc:Ignorable="d"
Title="MainWindow"
Height="350"
Width="525">
<StackPanel>
<ListBox x:Name='FruitList'>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='10*' />
<ColumnDefinition Width='10*' />
<ColumnDefinition Width='1*' />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text='{Binding FruitName}'
Grid.Column='0' />
<TextBlock Text='{Binding FruitColor}'
Grid.Column='1' />
<CheckBox IsChecked='{Binding Selected}'
Grid.Column='2' />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
还有我的代码:
namespace TestWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FruitList.ItemsSource = Fruits.getAllFruit();
}
}
}
使用绑定数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestWPF.Models
{
public class Fruit
{
public string FruitName { get; set; }
public string FruitColor { get; set; }
public bool Selected { get; set; }
}
}
namespace TestWPF.Models
{
public class Fruits
{
private static List<Fruit> _fruitList;
static Fruits()
{
_fruitList = new List<Fruit>();
_fruitList.Add(new Fruit
{
FruitName = "Mango",
FruitColor = "Yellow",
Selected = false
});
_fruitList.Add(new Fruit
{
FruitName = "Mango",
FruitColor = "Yellow",
Selected = false
});
_fruitList.Add(new Fruit
{
FruitName = "Water Melon",
FruitColor = "Green",
Selected = false
});
_fruitList.Add(new Fruit
{
FruitName = "Apple",
FruitColor = "Red",
Selected = false
});
_fruitList.Add(new Fruit
{
FruitName = "Banana",
FruitColor = "Yellow",
Selected = false
});
_fruitList.Add(new Fruit
{
FruitName = "Orange",
FruitColor = "Orange",
Selected = false
});
}
public static List<Fruit> getAllFruit(bool bSelected = false)
{
var result = (bSelected ?
_fruitList.Where(x => x.Selected = true).ToList<Fruit>()
: _fruitList.ToList<Fruit>());
return result;
}
}
}
【问题讨论】:
标签: c# wpf datatemplate