1. 程式人生 > 其它 >WPF 模板選擇器

WPF 模板選擇器

模板選擇器:根據內容可以自定義呼叫不同的模板

//模板選擇器類

public class PersonDataTemplateSelector : DataTemplateSelector
{
public DataTemplate NormalTemplate { get; set; }
public DataTemplate HightlightTemplate { get; set; }
public int MinAge { get; set; }
public int MaxAge { get; set; }
public string PropName { get; set; }
public string NameValue { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
Person person = item as Person;

var result = person.GetType().GetProperty(PropName).GetValue(person);
//if (person.Age > MinAge && person.Age <= MaxAge)
//{
// return HightlightTemplate;
//}
if (result.ToString() == NameValue)
{
return HightlightTemplate;
}

return NormalTemplate;
}
}

//呼叫模板選擇器類

<ListView ItemsSource="{DynamicResource array}">
<ListView.ItemTemplateSelector>
<local:PersonDataTemplateSelector NormalTemplate="{StaticResource normalDt}"
HightlightTemplate="{StaticResource highlightDt}"
MinAge="28" MaxAge="30"
PropName="Name" NameValue="Ace"/>
</ListView.ItemTemplateSelector>


</ListView>