本文介绍了WPF绑定查看内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与一些code,我需要在XAML定义控制模式,混合编程方式创建的控件进行实验。
有人可以解释为什么当我绑定到元素视图属性,属性的'得到'被调用了两次,但绑定到Template属性,当它被调用一次(如预期)。
示例输出时,结合景观:
StringElement
StringElement
BoolElement
BoolElement
StringElement
StringElement
示例输出时绑定到模板:
StringElement
BoolElement
StringElement
-
<窗口x:类=BindView.MainWindow
的xmlns =http://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
的xmlns:X =http://schemas.microsoft.com/winfx/2006/xaml
标题=主窗口WindowStartupLocation =中心屏幕>
<的ItemsControl的ItemsSource ={绑定元素}>
< ItemsControl.ItemTemplate>
<&DataTemplate的GT;
<内容presenter CONTENT ={绑定视图}/>
< / DataTemplate中>
<! - <&DataTemplate的GT;
<内容presenter的ContentTemplate ={绑定模板}/>
&所述; /的DataTemplate&GT - →;
< /ItemsControl.ItemTemplate>
< / ItemsControl的>
公共抽象类元素
{
公众的DataTemplate模板
{
得到
{
Console.WriteLine(的GetType()名称。);
返回OnGetTemplate();
}
} 公共抽象的DataTemplate OnGetTemplate(); 公众的UIElement查看
{
得到
{
Console.WriteLine(的GetType()名称。);
返回OnGetView();
}
} 公共抽象的UIElement OnGetView(); 受保护的DataTemplate CreateTemplate(类型viewType)
{
VAR XAML =的String.Format(<&DataTemplate的GT;< {0} />< / DataTemplate中>中,viewType.Name);
VAR语境=新ParserContext(); context.XamlTypeMapper =新XamlTypeMapper(新的字符串[0]);
context.XmlnsDictionary.Add(,http://schemas.microsoft.com/winfx/2006/xaml/$p$psentation);
context.XmlnsDictionary.Add(×,http://schemas.microsoft.com/winfx/2006/xaml); 返回(DataTemplate中)XamlReader.Parse(XAML,背景);
}
}公共类StringElement:元
{
公众覆盖的DataTemplate OnGetTemplate(){返回CreateTemplate(typeof运算(文本框)); }
公众覆盖的UIElement OnGetView(){返回新的TextBox(); }
}公共类BoolElement:元
{
公众覆盖的DataTemplate OnGetTemplate(){返回CreateTemplate(typeof运算(复选框)); }
公众覆盖的UIElement OnGetView(){返回新的复选框(); }
}公共部分类主窗口:窗口
{
公开名单<组件>元素{搞定;私人集; } 公共主窗口()
{
元素=新的List<组件>(){新StringElement(),新BoolElement(),新StringElement()};
的DataContext =这一点;
的InitializeComponent();
}
}
解决方案
从微软阅读:问题结合图像 - 属性为每个项目叫了两声
Basically you can't rely the getter for a DependencyObject to be called exactly once.
这篇关于WPF绑定查看内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!