请教WPF高手关于DataTemplate的属性vue绑定自定义属性问题

通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelector。请注意,如果具有不同类型的对象,则可以对 DataTemplate 设置 DataType 属性。如果您执行了此操作,则无需创建 DataTemplateSelector。此外,如果对象类型相同但属性不同,也可以考虑使用 DataTrigger 或数据转换器。
通俗讲,就是根据不同的数据选择不同的模板。接下来,我用一个例子来讲述DataTemplateSelector和动态绑定的使用方法。
下面例子如图,只要年龄大于50的使用一种模板,否则另一种模板,并在年龄大于50的模板中是男性的添加触发器使用背景变成蓝色的。
1、创建模板选择器
public class MyDataTemplateSelector : DataTemplateSelector
public override DataTemplate SelectTemplate(object item, DependencyObject container)
var fe = container as FrameworkE
var obj = item as P
DataTemplate dt = null;
if (obj != null && fe != null)
if (obj.age & <span style="color: #)
dt = fe.FindResource("one") as DataT
dt = fe.FindResource("two") as DataT
2、界面设计:
&Window x:Class="WpfApplication5.MainWindow"
xmlns="/winfx/2006/xaml/presentation"
xmlns:x="/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication5"
Title="MainWindow" Height="<span style="color: #0" Width="<span style="color: #5"&
&Window.Resources&
&local:MyDataTemplateSelector
x:Key="mydt"&&/local:MyDataTemplateSelector&
&DataTemplate x:Key="one"&
&Border BorderThickness="<span style="color: #" BorderBrush="red" Background="AliceBlue"&
&StackPanel Orientation="Horizontal" Name="skp" &
&TextBlock Text="{Binding name}" Margin="<span style="color: #"&&/TextBlock&
&TextBlock Text="{Binding age}" Margin="<span style="color: #"&&/TextBlock&
&TextBlock Text="{Binding sex}" Margin="<span style="color: #"&&/TextBlock&
&/StackPanel&
&DataTemplate.Triggers&
&DataTrigger
Value="男" Binding="{Binding Path=sex}"&
&Setter TargetName="skp" Property="Background" Value="CornflowerBlue" /&
&/DataTrigger&
&/DataTemplate.Triggers&
&/DataTemplate&
&DataTemplate x:Key="two" &
&Border BorderThickness="<span style="color: #" BorderBrush="Blue" Background="YellowGreen" Padding="<span style="color: #" &
&StackPanel Orientation="Horizontal"&
&TextBlock Text="{Binding name}"
Margin="<span style="color: #"&&/TextBlock&
&TextBlock Text="{Binding age}" Margin="<span style="color: #"&&/TextBlock&
&TextBlock Text="{Binding sex}" Margin="<span style="color: #"&&/TextBlock&
&/StackPanel&
&/DataTemplate&
&/Window.Resources&
&ListBox Name="lb" ItemTemplateSelector="{StaticResource mydt}"&
&/ListBox&
public partial class MainWindow : Window
public MainWindow()
InitializeComponent();
LoadData();
lb.ItemsSource =
public List&Person& list { get; set; }
public void LoadData()
Random r = new Random();
list = new List&Person&();
for (int i = <span style="color: #; i & <span style="color: #; i++)
list.Add(new Person
name = "张三" + i,
age = r.Next(<span style="color: #0)
public class Person
public string name { get; set; }
public int age { get; set; }
阅读(...) 评论()解决DataTemplate绑定附加属性
作者:用户
本文讲的是解决DataTemplate绑定附加属性 ,
文 Silverlight 版本:4.0。
首先定义数据类型,此文始终使用此定义类型。
view sourceprint?
public class SimpleData : Vie
文 Silverlight 版本:4.0。
首先定义数据类型,此文始终使用此定义类型。
view sourceprint?
public class SimpleData : ViewModelBase
private string _
private int _column, _
public string Text { get { return _ } set { _text = OnPropertyChanged("Text"); } }
public int Column { get { return _ } set { _column = OnPropertyChanged("Column"); } }
public int Row { get { return _ } set { _row = OnPropertyChanged("Row"); } }
前台代码:
view sourceprint?
&Grid x:Name="LayoutRoot" Background="White"&
&ItemsControl ItemsSource="{Binding}"&
&ItemsControl.ItemTemplate&
&DataTemplate&
&TextBox Text="{Binding Text}"
Foreground="Green"
Grid.Row="{Binding Row}"
Grid.Column="{Binding Column}"
Height="30" Width="150"
&/DataTemplate&
&/ItemsControl.ItemTemplate&
&ItemsControl.ItemsPanel&
&ItemsPanelTemplate&
&Grid ShowGridLines="True"&
&Grid.RowDefinitions&
&RowDefinition/&
&RowDefinition/&
&RowDefinition/&
&/Grid.RowDefinitions&
&Grid.ColumnDefinitions&
&ColumnDefinition/&
&ColumnDefinition/&
&/Grid.ColumnDefinitions&
&/ItemsPanelTemplate&
&/ItemsControl.ItemsPanel&
&/ItemsControl&
后台代码:
view sourceprint?
public partial class MainPage : UserControl
public MainPage()
InitializeComponent();
this.DataContext = new SimpleData[]
new SimpleData{ Text = "111111", Column = 0, Row = 0 },
new SimpleData{ Text = "222222", Column = 1, Row = 1 },
new SimpleData{ Text = "333333", Column = 0, Row = 2 },
可以看出这段代码的本意是通过绑定的方式设置,在 ItemsControl 里面显示 3 个 TextBox,同时指定了相应在 Grid 的行和列。
但是,你懂的!
这样的代码肯定是不能正确运行。特别是在Silverlight。
如果这是在 WPF 环境,很庆幸你还可以用 ItemContainerStyle 搞定:
view sourceprint?
&ItemsControl.ItemContainerStyle&
&Setter Property="Grid.Row" Value="{Binding Row, Mode=OneWay}"/&
&Setter Property="Grid.Column" Value="{Binding Column, Mode=OneWay}"/&
&/ItemsControl.ItemContainerStyle&
只可惜这是在 Silverlight 环境。我们只能够想别的办法了。
为什么不可以?拿出 Silverlight Spy 或者 Snoop 查看相应的 VisualTree。可以看到在 TextBox 外面还套了一个 ContextPresenter。
于是我们可以想到,能不能设置 ContextPresenter 的 Grid.Row 和 Grid.Colume 达到控制行列的目的?
于是我们得到下面的思路,使用附加属性把相应的绑定关系提升。
view sourceprint?
using System.Collections.G
using System.G
using System.L
using System.R
using System.W
using System.Windows.C
using System.Windows.D
using System.Windows.M
namespace Delay
public class UpUp : DependencyObject
// Using a DependencyProperty as the backing store for Up.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty UpProperty =
DependencyProperty.RegisterAttached("Up", typeof(string), typeof(UpUp), new PropertyMetadata(string.Empty));
public static void SetUp(FrameworkElement element, string value)
HanderClosure hander = element.GetValue(UpProperty) as HanderC
if (hander == null)
hander = new HanderClosure(element, value);
element.SetValue(UpProperty, value);
element.LayoutUpdated += new EventHandler(hander.element_LayoutUpdated);
public static string GetUp(FrameworkElement element)
HanderClosure hander = element.GetValue(UpProperty) as HanderC
if (hander == null)
return null;
return hander.OrgP
private class HanderClosure
private FrameworkElement _elem = null;
private string[] propertys = null;
private int _
private UpMode _
private string _orgP
public string OrgParamenter { get { return _orgP } }
public HanderClosure(FrameworkElement element, string parameter)
if (element == null)
throw new ArgumentNullException("element");
if (parameter == null)
throw new ArgumentNullException("parameter");
_level = 1;
_mode = UpMode.C
_orgParamenter =
string[] array = parameter.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (array.Length == 0)
throw new ArgumentException("parameter");
propertys = array[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (array.Length & 1)
if (int.TryParse(array[1].Trim(), out num))
if (array.Length & 2)
if (Enum.TryParse&UpMode&(array[2].Trim(), true, out mode))
public void element_LayoutUpdated(object sender, EventArgs e)
FrameworkElement parent = _
for (int i = 0; i & _level && parent != null; i++)
parent = VisualTreeHelper.GetParent(parent) as FrameworkE
if (parent == null)
foreach (string property in propertys)
Apply(_elem, parent, property.Trim());
// Copyright (C) Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the Microsoft Public License
// (Ms-PL, http://opensource.org/licenses/ms-pl.html).
private void Apply(FrameworkElement element1, FrameworkElement element2, string property)
var array = property.Split('.');
if (array.Length != 2)
throw new ArgumentException("property");
string typeName = array[0].Trim();
string propertyName = array[1].Trim();
Type type = null;
foreach (var assembly in AssembliesToSearch)
// Match on short or full name
type = assembly.GetTypes()
.Where(t =& (t.FullName == typeName) || (t.Name == typeName))
.FirstOrDefault();
if (type != null)
if (null == type)
// Unable to find the requested type anywhere
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
"Unable to access type "{0}". Try using an assembly qualified type name.",
typeName));
// Get the DependencyProperty for which to set the Binding
DependencyProperty dp = null;
var field = type.GetField(
propertyName + "Property",
BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);
if (null != field)
dp = field.GetValue(null) as DependencyP
if (null == dp)
// Unable to find the requsted property
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
"Unable to access DependencyProperty "{0}" on type "{1}".",
propertyName,
type.Name));
BindingExpression binding = element1.GetBindingExpression(dp);
object value = element1.GetValue(dp);
if (binding != null)
element2.SetBinding(dp, binding.ParentBinding);
else if (value != null)
element2.SetValue(dp, value);
if (_mode == UpMode.Move)
element1.ClearValue(dp);
// Copyright (C) Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the Microsoft Public License
// (Ms-PL, http://opensource.org/licenses/ms-pl.html).
/// &summary&
/// Gets a sequence of assemblies to search for the provided type name.
/// &/summary&
private IEnumerable&Assembly& AssembliesToSearch
// Start with the System.Windows assembly (home of all core controls)
yield return typeof(Control).A
#if SILVERLIGHT && !WINDOWS_PHONE
// Fall back by trying each of the assemblies in the Deployment's Parts list
foreach (var part in Deployment.Current.Parts)
var streamResourceInfo = Application.GetResourceStream(
new Uri(part.Source, UriKind.Relative));
using (var stream = streamResourceInfo.Stream)
yield return part.Load(stream);
private enum UpMode
如何使用?使用非常简单!
在你的项目中增加 UpUp 之后,在需要提升绑定级别的 Page 的 Xaml 中引入命名空间 xmlns:delay="clr-namespace:Delay"。然后在需要提升绑定级别的控件中加入属性 delay:UpUp.Up="Grid.Row,Grid.Column"。得到完整的前台代码如下:
view sourceprint?
&UserControl x:Class="TestValueBindingInItemTemplate.MainPage"
xmlns="/winfx/2006/xaml/presentation"
xmlns:x="/winfx/2006/xaml"
xmlns:d="/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:delay="clr-namespace:Delay"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"&
&Grid x:Name="LayoutRoot" Background="White"&
&ItemsControl ItemsSource="{Binding}"&
&ItemsControl.ItemTemplate&
&DataTemplate&
&TextBox Text="{Binding Text}"
Foreground="Green"
Grid.Row="{Binding Row}"
Grid.Column="{Binding Column}"
Height="30" Width="150"
delay:UpUp.Up="Grid.Row,Grid.Column"
&/DataTemplate&
&/ItemsControl.ItemTemplate&
&ItemsControl.ItemsPanel&
&ItemsPanelTemplate&
&Grid ShowGridLines="True"&
&Grid.RowDefinitions&
&RowDefinition/&
&RowDefinition/&
&RowDefinition/&
&/Grid.RowDefinitions&
&Grid.ColumnDefinitions&
&ColumnDefinition/&
&ColumnDefinition/&
&/Grid.ColumnDefinitions&
&/ItemsPanelTemplate&
&/ItemsControl.ItemsPanel&
&/ItemsControl&
&/UserControl&
UpUp.Up 应该如何填写?实际上 UpUp.Up 属性有具体的语法格式:
UpUp.Up="Type.Property[,Type.Property ...][;Level[;Move|Copy]]"
Type.Property 是需要提升绑定关系的属性名称,可以用逗号把多个属性名称隔开。
Level 是整数,表示需要提升的层次。在 VisualTree 中向上一层为一个层次。
Move|Copy 是枚举类型,表示提升之后保留原来的绑定关系。
例如:delay:UpUp.Up="Grid.Row,Grid.C1;Copy"
有了 UpUp 之后,对于类似的绑定问题可以轻而易举的完成了!
PS:WPF 也可以用此方法实现,但是有细节方面的差异。
1、不能够使用SetXXX GetXXX,要使用 XXX 属性。
2、需要注册 PropertyChangedCallback 事件,并将相关注册 Hander 部分放置到此方法内。
以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索string
wpf datatemplate绑定、wpf datatemplate、datatemplate、emptydatatemplate、celltemplate数据绑定,以便于您获取更多的相关知识。
稳定可靠、可弹性伸缩的在线数据库服务,全球最受欢迎的开源数据库之一
6款热门基础云产品6个月免费体验;2款产品1年体验;1款产品2年体验
弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率
开发者常用软件,超百款实用软件一站式提供
云栖社区()为您免费提供相关信息,包括
,所有相关内容均不代表云栖社区的意见!wpf 模板选择器DataTemplateSelector及动态绑定使用教程 | 熊窝窝
其实也说不上算是教程了,只是把自己学习的代码拿出来分享一下,同时方便以后遇到类似问题的时候翻一下。
MSDN里如是说:
通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelector。请注意,如果具有不同类型的对象,则可以对 DataTemplate 设置 DataType 属性。如果您执行了此操作,则无需创建 DataTemplateSelector。此外,如果对象类型相同但属性不同,也可以考虑使用 DataTrigger 或数据转换器。
通俗讲,就是根据不同的数据选择不同的模板。接下来,我用一个例子来讲述DataTemplateSelector和动态绑定的使用方法。
先看例子的UI:
一个Listbox三个button,listbox显示一个集合的数据,第一个button &#8220;change&#8221;点击后可以切换与listbox绑定的集合,第二个button给PersonCollection添加person实例,第三个button给AnimalCollection添加animal实例。
默认情况下listbox与PersonCollection绑定,程序启动后,点击Add person按钮会向PersonCollection添加一个person实例,listbox会显示该集合下数据,如果person类的gender属性为Female,则只显示name属性,并把边框改成蓝色。点击change后,listbox与AnimalCollection绑定,显示AnimalCollection数据,同样,Add animal添加animal实例,如果第二个属性不是4,则只显示animal的type属性,并修改边框为蓝色。
下面讲实现
第一步:建两个类,一个person,一个animal,这就是每个listbox item将来要显示的数据。
1234567891011121314151617181920212223242526272829303132333435363738394041424344//person类
& & public class person : INotifyPropertyChanged
& & &#123;
& & & & public event PropertyChangedEventHandler PropertyChanged;
& & & & private string _name;
& & & & public string name
& & & & &#123;
& & & & & & get
& & & & & & &#123;
& & & & & & & & return _name;
& & & & & & &#125;
& & & & & & set
& & & & & & &#123;
& & & & & & & & if &#40;value != _name&#41;
& & & & & & & & &#123;
& & & & & & & & & & _name = value;
& & & & & & & & & & prochanged&#40;&name&&#41;;
& & & & & & & & &#125;
& & & & & & &#125;
& & & & &#125;
& & & & private string _gender;
& & & & public string gender
& & & & &#123;
& & & & & & get
& & & & & & &#123;
& & & & & & & & return _gender;
& & & & & & &#125;
& & & & & & set
& & & & & & &#123;
& & & & & & & & if &#40;value != _gender&#41;
& & & & & & & & &#123;
& & & & & & & & & & _gender = value;
& & & & & & & & & & prochanged&#40;&gender&&#41;;
& & & & & & & & &#125;
& & & & & & &#125;
& & & & &#125;
& & & & private void prochanged&#40;string info&#41;
& & & & &#123;
& & & & & & if &#40;PropertyChanged != null&#41;
& & & & & & &#123;
& & & & & & & & PropertyChanged&#40;this,
PropertyChangedEventArgs&#40;info&#41;&#41;;
& & & & & & &#125;
& & & & &#125;
& & &#125;
注意到这里,实现了INotifyPropertyChanged接口,需要引用命名空间ponentModel.因为我希望这些属性改变的时候,listboxitem能自动更新,关于INotifyPropertyChanged接口,请看我另一篇日志。
另一个类,animal与person基本类似,只是把person类里的属性:name和gender改成了type和legs。这里我就不贴代码了。
第二步:创建类DataContainer,包含两个集合,存储animal和person实例。代码:
12345678910& & public class DataContainer
& & &#123;
& & & & public &ObservableCollection&person& PersonCollection &#123; get;set; &#125;
& & & & public &ObservableCollection&animal& AnimalCollection &#123; get; set; &#125;
& & & & public DataContainer&#40;&#41;
& & & & &#123;
& & & & & & PersonCollection =
ObservableCollection&person&&#40;&#41;;
& & & & & & AnimalCollection =
ObservableCollection&animal&&#40;&#41;;
& & & & &#125;
& & &#125;
我用了ObservableCollection,因为ObservableCollection已经实现了INotifyPropertyChanged接口,所以如果集合的项增删的时候UI会自动更新。(using System.Collections.ObjectM//ObservableCollection)
注意:假设最上面第一段代码person类里面,没有实现INotifyPropertyChanged接口,而这里仍然使用ObservableCollection来存储person列表的话,PersonCollection 里的项增加或删除时,UI的listbox也会相应的增删,但是当你想修改PersonCollection里某一个person实例的属性,比如gender由male变成female时,UI并不会更新,因为PersonCollection 并没变。所以,当你希望改变UI listbox item里某个person的属性时,person类就需要实现INotifyPropertyChanged接口。
第三步:定义数据模板。
当然首先在窗口里把需要的listbox和button放好。我的XAML代码如下:
1234567& & &Grid&
& & & & &ListBox Margin=&12,12,12,60& Name=&listBox1& & HorizontalContentAlignment =&Stretch& ItemTemplateSelector=&{StaticResource mytemplate_selector}&&
& & & & &/ListBox&
& & & & &Button Height=&23& HorizontalAlignment=&Left& Margin=&12,0,0,12& Name=&Change& VerticalAlignment=&Bottom& Width=&75& Click=&Change_Click&&Change&/Button&
& & & & &Button Height=&23& Margin=&120,0,109,12& Name=&addperson& VerticalAlignment=&Bottom& Click=&addperson_Click&&Add person&/Button&
& & & & &Button Height=&23& HorizontalAlignment=&Right& Margin=&0,0,12,12& Name=&addanimal& VerticalAlignment=&Bottom& Width=&75& Click=&addanimal_Click&&Add animal&/Button&
& & &/Grid&
吃饭去了,回来再写……
继续,上面的XAML里的3个button没什么好说的,listbox里,最重要的一句是:ItemTemplateSelector=&#8221;{StaticResource mytemplate_selector}&#8221;,从字面意思理解,就是把一个叫做mytemplate_selector的静态资源,做为listbox的模板选择器。所以,接下来,定义我们需要资源,包括一个模板选择器和四个数据模板。模板选择器就是这里的mytemplate_selector,四个模板,person和animal各两个,通过模板选择器选择使用哪一个。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253& & &Window.Resources&
& & & & &local:MyDataTemplateSelector x:Key=&mytemplate_selector& /&
& & & & &DataTemplate x:Key =&person_template&&
& & & & & & &Border &Name=&myborder& BorderBrush=&Blue& Padding=&5& Margin=&2& BorderThickness=&1&&
& & & & & & &StackPanel&
& & & & & & & & &TextBlock &Text=&{Binding Path=name}&&&/TextBlock &
& & & & & & & & &TextBlock &Text=&{Binding Path=gender}&&&/TextBlock &
& & & & & & &/StackPanel&
& & & & & & &&/Border&
& & & & & & &DataTemplate.Triggers&
& & & & & & & & &DataTrigger &Value=&Male& Binding=&{Binding Path=gender}&& & & & & &
& & & & & & & & & & &Setter TargetName=&myborder& Property=&BorderBrush& Value=&Red& /&
& & & & & & & & &/DataTrigger&
& & & & & & &/DataTemplate.Triggers&
& & & & &/DataTemplate&
& & & & &DataTemplate x:Key=&male_template&&
& & & & & & &DataTemplate.Resources&
& & & & & & & & &Style TargetType=&TextBlock&&
& & & & & & & & & & &Setter Property=&FontSize& Value=&20& /&
& & & & & & & & &/Style&
& & & & & & &/DataTemplate.Resources&
& & & & & & &Border &Name=&myborder_male& BorderBrush=&Blue& Padding=&5& Margin=&2& BorderThickness=&1&&
& & & & & & & & &DockPanel&
& & & & & & & & & & &TextBlock Text=&{Binding Path=name}&/&
& & & & & & & & &/DockPanel&
& & & & & & &/Border&
& & & & &/DataTemplate&
& & & & &DataTemplate x:Key =&animal_template&&
& & & & & & &Border &Name=&myborder& BorderBrush=&Blue& Padding=&5& Margin=&2& BorderThickness=&1&&
& & & & & & & & &StackPanel&
& & & & & & & & & & &TextBlock &Text=&{Binding Path=type}&&&/TextBlock &
& & & & & & & & & & &TextBlock &Text=&{Binding Path=legs}&&&/TextBlock &
& & & & & & & & &/StackPanel&
& & & & & & &/Border&
& & & & & & &DataTemplate.Triggers&
& & & & & & & & &DataTrigger &Value=&4& Binding=&{Binding Path=legs}&&
& & & & & & & & & & &Setter TargetName=&myborder& Property=&BorderBrush& Value=&Red& /&
& & & & & & & & &/DataTrigger&
& & & & & & &/DataTemplate.Triggers&
& & & & &/DataTemplate&
& & & & &DataTemplate x:Key=&fourlegs_template&&
& & & & & & &DataTemplate.Resources&
& & & & & & & & &Style TargetType=&TextBlock&&
& & & & & & & & & & &Setter Property=&FontSize& Value=&20& /&
& & & & & & & & &/Style&
& & & & & & &/DataTemplate.Resources&
& & & & & & &Border &Name=&myborder_male& BorderBrush=&Blue& Padding=&5& Margin=&2& BorderThickness=&1&&
& & & & & & & & &DockPanel&
& & & & & & & & & & &TextBlock Text=&{Binding Path=type}&/&
& & & & & & & & &/DockPanel&
& & & & & & &/Border&
& & & & &/DataTemplate&
& & &/Window.Resources&
分析前面的XAML,在里面,我们共定义了五个资源,我简单分析一下前三个,后面两个跟第二个、第三个差不多,就不说多了。
第一个资源,定义了一个模板选择器,使用CS文件里的MyDataTemplateSelector类来选择模板。第二个资源,person_template, StackPanel里定义了普通的模板,显示person的name和gender,DataTrigger里定义了一个触发器,当gender为Male的时候,将item的border变成红色。这就是前面UI里不同的边框色的实现关键点。第三个资源male_template,定义了一个Male专用的模板,字体20号,只显示name。person_template模板里,边框颜色的变换通过DataTrigger就能实现,因为要修改的属性是在模板里存在的。但是当你想修改一些模板里不存的属性或者对于gender = male时使用另外完全不同的模板,那就要用到模板选择器了。下面分析前面提到的模板选择器,看着比较多,其实很简单,忍一忍认真点儿看完,你就能有更多收获。
12345678910111213141516171819202122232425262728293031323334353637//必须继承自DataTemplateSelector
&public class MyDataTemplateSelector:DataTemplateSelector
& & &#123;
& & & & //覆盖SelectTemplate函数
& & & & public override DataTemplate SelectTemplate&#40;object item, DependencyObject container&#41;
& & & & &#123;
& & & & & & Window win = Application.Current.MainWindow;
& & & & & & //当前正在显示的是person类数据时:
& & & & & & if &#40;item != null && item
person&#41;
& & & & & & &#123; & & & & & & &
& & & & & & & & person p = item as person;
& & & & & & & & //如果gender是male,将person_template做为现在的模板
& & & & & & & & if &#40;p.gender==&Male&&#41;
& & & & & & & & &#123;
& & & & & & & & & & return win.FindResource&#40;&person_template&&#41; as DataTemplate;
& & & & & & & & &#125;
& & & & & & & & //否则就使用male_template
& & & & & & & & else
& & & & & & & & &#123;
& & & & & & & & & & return win.FindResource&#40;&male_template&&#41; as DataTemplate;
& & & & & & & & &#125;
& & & & & & &#125;
& & & & & & else if&#40;item != null && item
animal&#41;
& & & & & & &#123;
& & & & & & & & animal a = item as animal;
& & & & & & & & if &#40;a.legs==4&#41;
& & & & & & & & &#123;
& & & & & & & & & & return win.FindResource&#40;&animal_template&&#41; as DataTemplate;
& & & & & & & & &#125;
& & & & & & & & else
& & & & & & & & &#123;
& & & & & & & & & & return win.FindResource&#40;&fourlegs_template&&#41; as DataTemplate;
& & & & & & & & &#125;
& & & & & & &#125;
& & & & & & return null;
& & & & &#125;
& & &#125;
程序初初始化的时候:
1234567891011& & & & private bool isPersonDisplaying;
& & & & private DataContainer dc;
& & & & public Window1&#40;&#41;
& & & & &#123;
& & & & & & InitializeComponent&#40;&#41;;
& & & & & & //表示当前正在显示的数据。默认显示person
& & & & & & isPersonDisplaying = true;
& & & & & & dc =
DataContainer&#40;&#41;;
& & & & & & //指定数据源
& & & & & & listBox1.ItemsSource = dc.PersonCollection;
& & & & &#125;
三个按钮的函数,change:
1234567891011121314151617private void Change_Click&#40;object sender, RoutedEventArgs e&#41;
& & & & &#123;
& & & & & & changeBindingPath&#40;&#41;;
& & & & &#125;
& & & & private void changeBindingPath&#40;&#41;
& & & & &#123;
& & & & & & if &#40;isPersonDisplaying&#41;
& & & & & & &#123;
& & & & & & & & listBox1.ItemsSource = dc.AnimalCollection;
& & & & & & & & isPersonDisplaying = false;
& & & & & & &#125;
& & & & & & else
& & & & & & &#123;
& & & & & & & & listBox1.ItemsSource = dc.PersonCollection;
& & & & & & & & isPersonDisplaying = true;
& & & & & & &#125;
& & & & &#125;
这里实现不同数据源的切换,当数据源变换的时候,WPF会调用前面我们定义的模板选择器,选择正确的模板。
两个增加数据的函数:
12345678910111213141516&private void addperson_Click&#40;object sender, RoutedEventArgs e&#41;
& & & & &#123;
& & & & & & person p =
person&#40;&#41;;
& & & & & & p.name = &PersonName& + System.DateTime.Now.Second.ToString&#40;&#41;;
& & & & & & string gender = &#40;System.DateTime.Now.Second%2&#41;==1?&Male&:&Female&;
& & & & & & p.gender = gender;
& & & & & & dc.PersonCollection.Add&#40;p&#41;;
& & & & &#125;
& & & & private void addanimal_Click&#40;object sender, RoutedEventArgs e&#41;
& & & & &#123;
& & & & & & animal a =
animal&#40;&#41;;
& & & & & & a.type = &AnimalType& + System.DateTime.Now.Second.ToString&#40;&#41;;
& & & & & & a.legs = &#40;System.DateTime.Now.Second % 2&#41; == 1 ? 2 : 4;
& & & & & & dc.AnimalCollection.Add&#40;a&#41;;
& & & & &#125;
表达能力一般,水平一般,大家见谅。源代码我打了个包,,编译环境:vs2008。
本条目发布于。属于分类。作者是。
有人回复时邮件通知我
2017年八月 &(1)
2017年一月 &(2)
2016年七月 &(1)
2016年四月 &(1)
2016年二月 &(1)
2016年一月 &(5)
2015年十一月 &(2)
2015年十月 &(84)
2015年五月 &(2)
2015年四月 &(2)
2015年二月 &(1)
2015年一月 &(2)
2014年十二月 &(4)
2014年十一月 &(3)
2014年十月 &(1)
2014年九月 &(4)
2014年八月 &(1)
2014年四月 &(4)
2014年三月 &(8)
2014年二月 &(1)
2014年一月 &(1)
2013年三月 &(2)
2013年二月 &(2)
2012年十二月 &(2)
2012年十一月 &(2)
2012年九月 &(2)
2012年八月 &(3)
2012年七月 &(3)
2012年六月 &(2)
2012年五月 &(1)
2012年四月 &(2)
2012年二月 &(1)
2012年一月 &(1)
2011年十月 &(1)
2011年八月 &(1)
2011年七月 &(2)
2011年六月 &(14)
2011年五月 &(6)
2011年四月 &(9)
2011年三月 &(2)
2011年一月 &(7)
2010年十二月 &(8)
2010年十一月 &(1)
2010年十月 &(4)
2010年九月 &(1)
2010年八月 &(2)
2010年七月 &(3)
2010年六月 &(10)
2010年五月 &(6)
2010年四月 &(15)
2010年三月 &(17)
2010年二月 &(15)
2010年一月 &(26)
2009年十二月 &(22)
2009年十一月 &(35)
2009年十月 &(18)
2009年九月 &(5)
2009年八月 &(3)
2009年七月 &(1)
2009年六月 &(1)
2009年五月 &(2)
2009年四月 &(7)}

我要回帖

更多关于 angular 绑定属性 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信