【问题标题】:Update DataTemplate on PropertyChanged does not work在 PropertyChanged 上更新 DataTemplate 不起作用
【发布时间】:2018-05-03 14:48:51
【问题描述】:

我有一个简单的对象 Action,它有一个属性 Code。根据其代码,我想选择不同的数据模板,用户也可以通过组合框更改代码。

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

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

【问题讨论】:

  • 用调试器单步调试,看看发生了什么。它在哪里返回,当它返回时,一切的价值是什么?
  • @SeanO'Neil PropertyChanged 永远不会被调用。我正确更改了属性,但似乎没有收到通知

标签: c# wpf


【解决方案1】:

DataTemplateSelector 不响应属性更改通知。作为一种解决方法,您可以在ItemTemplate 中使用ContentControlDataTriggers,例如:

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

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多