wpf如何动态设置网格的宽度和高度?

WPF动态改变网格的行宽或列高,需要创建一个GridLength的动画类。

(1)创建一个支持GridLength类型的动画类。

创建一个继承AnimationTimeLine的新类GridLengthAnimation,简单实现两个依赖属性“From”、“to”和“To”。代码如下:

内部类GridLengthAnimation:animation timeline

{

静态GridLengthAnimation()

{

from property = dependency property。Register("From ",typeof(GridLength),

type of(GridLengthAnimation));

ToProperty = DependencyProperty。Register("To ",typeof(GridLength),

type of(GridLengthAnimation));

}

来自Property的公共静态只读DependencyProperty

公共电网从

{

得到

{

return(GridLength)GetValue(GridLengthAnimation。from property);

}

设置

{

SetValue(GridLengthAnimation。FromProperty,value);

}

}

public static readonly dependency property to property;

公共电网延伸至

{

得到

{

return(GridLength)GetValue(GridLengthAnimation。to property);

}

设置

{

SetValue(GridLengthAnimation。ToProperty,value);

}

}

接下来,我们将依次重载或实现AnimationTimeLine类的成员。

1.重载CreateInstanceCore,代码如下:

受保护的超驰系统。windows . freez able CreateInstanceCore()

{

返回新的GridLengthAnimation();

}

2.重载GetCurrentValue以返回动画的当前值。代码如下:

公共覆盖对象GetCurrentValue(对象defaultOriginValue,

对象defaultDestinationValue,动画时钟动画时钟)

{

double from val =((GridLength)GetValue(GridLengthAnimation。FromProperty))。价值;

double to val =((GridLength)GetValue(GridLengthAnimation。ToProperty))。价值;

if(from val & gt;托瓦尔)

{

返回新的网格长度((1 - animationClock。current progress . Value)*(from val-toVal)+toVal,

((GridLength)GetValue(GridLengthAnimation。FromProperty))。GridUnitType);

}

其他

返回新的GridLength(animationClock。current progress . Value *(toVal-from val)+from val

((GridLength)GetValue(GridLengthAnimation。ToProperty))。GridUnitType);

}

3.重写TargetPropertyType属性,以指示相应动画生成的输出类型。代码如下:

公共重写类型TargetPropertyType

{

得到

{

返回类型of(GridLength);

}

}

好了,通过以上步骤我们已经写好了GridLengthAnimation类,接下来就是如何使用了。

(2) xaml使用了这个类,代码如下:

& lt窗户。资源& gt

& lt故事板x:Key = " sb dock " & gt;

& ltcommon:GridLengthAnimation begin time = " 00:00:00 "情节提要。TargetName="_cellLeft "故事板。TargetProperty = " Width " & gt

& lt/common:GridLengthAnimation & gt;

& lt/story board & gt;

& lt/窗口。资源& gt

& ltgrid x:Name = " layout root " Background = " White " & gt;

& lt网格。RowDefinitions & gt

& ltRowDefinition/>

& lt/网格。RowDefinitions & gt

& lt网格。ColumnDefinitions & gt

& ltcolumn definition x:Name = " _ cell left " Width = " 300 "/& gt;

& ltcolumn definition x:Name = " _ cell right " Width = " * "/& gt;

& lt/网格。ColumnDefinitions & gt

& lt/Grid & gt;

(3) c#使用了这个类,代码如下:

故事板sbDock = this。find resource(“sb dock”)作为故事板;

如果(sbDock!=空)

{

splinedoublekey frame SD key frame 1 =新splinedoublekey frame(transform radius,

关键时刻。FromTimeSpan(TimeSpan。from seconds(1));

(sbDock。children[0]as doubleanimationusingkey frames). key frames . clear();

(sbDock。children[0]as doubleanimationusingkey frames). key frame . add(SD key frame 1);

(sbDock。Children[1]作为GridLengthAnimation)。From = new GridLength(300,GridUnitType。像素);

(sbDock。Children[1]作为GridLengthAnimation)。To = new GridLength(0,GridUnitType。像素);

sbDock。begin();

}