在XAML的開發中,能夠熟練的使用Grid布局是一個基本要求,本篇文章嘗試解決其中一個比較顯而易見的問題。
在Grid的布局的頁面中,相信下面的類似代碼一定非常熟悉:
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2">
雖然在Blend下可以很方便的修改布局參數,但是實際上我們很多時候都是直接在VS里面編輯XAML,所以本文的思路是用附加屬性來解決這個問題:
首先定義一個Cell屬性:
public static string GetCell(DependencyObject d)
{
return (string)d.GetValue(CellProperty);
}
public static void SetCell(DependencyObject d, string value)
{
d.SetValue(CellProperty, value);
}
public static readonly DependencyProperty CellProperty =
DependencyProperty.RegisterAttached("CellProperty", typeof(string), typeof(GridUtil), new PropertyMetadata(string.Empty, OnCellPropertyChanged));
那么關鍵點就在OnCellPropertyChanged如何處理了:
var locationDefs = e.NewValue as string;
var locationDefArray = locationDefs.Split(',');
for (int i = 0; i < locationDefArray.Length; i++)
{
string locationDef = locationDefArray[i].Trim();
if (string.IsNullOrEmpty(locationDef))
{
locationDef = "0";
}
int locationValue;
if (int.TryParse(locationDef, out locationValue))
{
switch (i)
{
case 0:
d.SetValue(Grid.RowProperty, locationValue);
break;
case 1:
d.SetValue(Grid.ColumnProperty, locationValue);
break;
case 2:
d.SetValue(Grid.RowSpanProperty, locationValue > 0 ? locationValue : 1);
break;
case 3:
d.SetValue(Grid.ColumnSpanProperty, locationValue > 0 ? locationValue : 1);
break;
}
}
}
其實顯而易見的是,我通過不同的參數去處理Grid的各個屬性,那么開頭一段XAML,現在就可以表示成下面的寫法:
<StackPanel GridMarkup:GridUtil.Cell="2,1,2"/>
其實也許你會覺得原生態的寫法更好,我只是通過這個例子給各位一點參考,希望對各位有幫助。
代碼下載:GridUtil.rar
另外幫自己的部門打個小廣告:招收熟悉C#+XAML開發的工程師,地點在南京,有意者請留言。