WPF,复制元素,为什么走样了?

fgfdybt456t 2014-04-03 07:50:16
一个自定义控件:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF2">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Height" Value="250"/>
<Setter Property="Width" Value="250"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Button x:Name="button" Content="fgffgfg" Height="20" Background="Red"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>


public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
button = this.GetTemplateChild("button") as Button;
aaa();
}
Button button;
public void aaa()
{
Button button2 = DeepCopy<Button>(this.button);
}
static T DeepCopy<T>(T obj)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
XamlWriter.Save(obj, stream);
stream.Seek(0, System.IO.SeekOrigin.Begin);
return (T)XamlReader.Load(stream);
}
}


主窗体:

<Window x:Class="WPF2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF2"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomControl1/>
</Grid>
</Window>


上面的代码中个,有一个自定义控件CustomControl1,在其控件模板内部,有一个Button,高度为20。
在重写OnApplyTemplate方法中,获取到了控件模板中的Button,并用变量button保存下来。
代码中有一个静态的DeepCopy<T>方法,这个方法是用来复制元素的。
在控件CustomControl1中,有一个方法aaa,其调用DeepCopy<T>方法,复制了控件模板中的button,并用变量button2保存
现在问题出来了:
我在方法aaa的结尾处,设置了断点,运行之后,查看了变量button和button2,发现button的高度为20,button2的高度却为NaN,高度的属性值发生了变化,请问,这是为什么呢?
...全文
260 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
霜寒月冷 2014-04-11
  • 打赏
  • 举报
回复
八成是自定义控件写的不灵活
fgfdybt456t 2014-04-11
  • 打赏
  • 举报
回复
帮顶..........
fgfdybt456t 2014-04-04
  • 打赏
  • 举报
回复
这是为什么啊?
fgfdybt456t 2014-04-04
  • 打赏
  • 举报
回复
有人知道不啊?
wpd202 2014-04-04
  • 打赏
  • 举报
回复
帮顶.................
fgfdybt456t 2014-04-03
  • 打赏
  • 举报
回复
在线求解....
fgfdybt456t 2014-04-03
  • 打赏
  • 举报
回复
有人知道吗?

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧