繁体   English   中英

在PropertyChanged上更新DataTemplate不起作用

[英]Update DataTemplate on PropertyChanged does not work

我有一个简单的对象Action,它具有属性Code。 根据其代码,我想选择不同的DataTemplates,用户也可以通过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; }
}

所以我在看这个答案: https : //stackoverflow.com/a/18000310/2877820

我试过实现这样的解决方案:

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;
}

不幸的是,它似乎对我不起作用。 有人可以帮我吗? 我在这里做错什么了吗?

DataTemplateSelector不响应属性更改通知。 作为一种变通方法,你可以使用一个ContentControlDataTriggersItemTemplate ,.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM