I have a simple object Action that has a property Code. Depending on its Code, I want to select different DataTemplates a it is also possible for the user to change the Code through a ComboBox.
public class Action : INotifyPropertyChanged
{
public Action()
{
Parameters = new List<Parameter>();
}
public int ActionID { get; set; }
public int StepID { get; set; }
public int Code { get; set; }
[NotMapped]
public List<Parameter> Parameters { get; set; }
}
So I was looking at this answer: https://stackoverflow.com/a/18000310/2877820
I tried the implement the solution like this:
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var action = (ASI.RecipeManagement.Data.Action) item;
if (action == null) return null;
PropertyChangedEventHandler lambda = null;
lambda = (o, args) =>
{
if (args.PropertyName == "Code")
{
action.PropertyChanged -= lambda;
var cp = (ContentPresenter)container;
cp.ContentTemplateSelector = null;
cp.ContentTemplateSelector = this;
}
};
action.PropertyChanged += lambda;
if (action.Code == 0)
return NoParamTemplate;
if (action.Code == 1)
return OneParamTemplate;
if (action.Code == 2)
{
if (action.Parameters[0].Type == ParameterInputTypes.List)
{
return ComboBoxParamTemplate;
}
return TwoParamTemplate;
}
return null;
}
Sadly it does not seem to work for me. Can anybody help me out? What am I doing wrong right here?
A DataTemplateSelector
does't respond to property change notifications. As a workaround, you could use a ContentControl
with DataTriggers
in the ItemTemplate
, .eg:
<ComboBox ...>
<ComboBox.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource NoParamTemplate}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Code}" Value="1">
<Setter Property="ContentTemplate" Value="{StaticResource OneParamTemplate}" />
</DataTrigger>
<DataTrigger Binding="{Binding Code}" Value="2">
<Setter Property="ContentTemplate" Value="{StaticResource TwoParamTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.