我已經創建了一個簡單的DataGridUnboundedColumn類,它是從DataGridBoundColumn派生的,可用於爲單元格提供FrameworkElement的自定義文本。
您只需訂閱CellFormating事件並將EventArgs中的CellElement設置爲將顯示的自定義元素。也可以在EventArgs中設置CellText - 在這種情況下,具有CellText的TextBlock將顯示在網格中。
下面的例子演示瞭如何使用它:
XAML:
<dg:DataGrid Name="DataGrid1" AutoGenerateColumns="False">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
<myColumn:DataGridUnboundedColumn x:Name="AddressColumn" Header="Address" />
</dg:DataGrid.Columns>
</dg:DataGrid>
CODE:
public MyPage()
{
InitializeComponent();
AddressColumn.CellFormating += new UnboundedColumnEventHandler(AddressColumn_CellFormating);
}
void AddressColumn_CellFormating(object sender, UnboundedColumnEventArgs e)
{
IPerson person;
person= e.DataItem as IPerson;
if (person!= null)
e.CellText = string.Format("{0}, {1} {2}", person.Address, person.PostalCode, person.City);
}
的DataGridUnboundedColumn實現是在這裏:
class DataGridUnboundedColumn : DataGridBoundColumn
{
public event UnboundedColumnEventHandler CellFormating;
public DataGridUnboundedColumn()
{
this.IsReadOnly = true;
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
return null;
}
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
FrameworkElement shownElement;
UnboundedColumnEventArgs eventArgs;
if (CellFormating == null)
return null;
eventArgs = new UnboundedColumnEventArgs(cell, dataItem);
// call the event
CellFormating(this, eventArgs);
shownElement = null;
// check the data set in the eventArgs
if (eventArgs.CellElement != null)
{
// show the set eventArgs.CellElement
shownElement = eventArgs.CellElement;
}
else if (eventArgs.CellText != null)
{
// show the CellText in TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Text = eventArgs.CellText;
shownElement = textBlock;
}
else
{
// nothing set
}
return shownElement;
}
}
public delegate void UnboundedColumnEventHandler(object sender, UnboundedColumnEventArgs e);
public class UnboundedColumnEventArgs : EventArgs
{
public DataGridCell Cell { get; set; }
public object DataItem { get; set; }
/// <summary>
/// The subscriber of the event can set the CellText.
/// In this case the TextBlock is used to display the text.
/// NOTE that if CellElement is not null, the CellText will not be used but insted a CellElement will be shown
/// </summary>
public string CellText { get; set; }
/// <summary>
/// The subscribed can set the FrameworkElement that will be shown for this cell.
/// If the CellElement is null, the CellText will be used to show the TextBlock
/// </summary>
public FrameworkElement CellElement { get; set; }
public UnboundedColumnEventArgs()
: base()
{ }
public UnboundedColumnEventArgs(DataGridCell cell, object dataItem)
: base()
{
Cell = cell;
DataItem = dataItem;
}
}
視圖模型方法是我考慮過的事情。然而,我無法弄清楚如何克服任何給定行不知道的基本障礙,我將擁有哪種類型的控件以及我將擁有多少控件。在那裏硬編碼一定數量並設置其可見度是不可能的。 – 2009-02-23 15:56:21
您可能更樂意迴避datagrid然後 - 看看我的編輯 – 2009-02-24 19:33:03