【问题标题】:Can you display the first element of a ListBox rather than create a data template for xaml您可以显示 ListBox 的第一个元素而不是为 xaml 创建数据模板吗
【发布时间】:2013-10-20 01:58:31
【问题描述】:

下面的绑定是在一个 IEnumerable 调用的活动上。问题是,在我的 xaml 中......我只想输出数组中的第一个元素。你能按照这些思路做点什么吗:

<Run Text="{Binding activity[0].created_by.name}"></Run>

或者您是否必须为活动 IEnumerable 数组链接另一个数据模板?

这是 ActivityStream 类的属性(我现在注意到它是一个 List..hmm。)

...
    [DataMember]
    public List<object> activity { get; set; }
...

这是我做 PropertyChanged yada yada 的地方

    public IEnumerable<JamesStream> activityStream;

...

    private async void LoadActivityStreamSection()
    {
        activityStreamRepository = new JamesStreamRepository();
        var tempActivityStream = await activityStreamRepository.GetAllBySpaceId(space.space_id);

        activityStream = tempActivityStream;
        ActivityStream = null;

        //The Activitiy Stream has a property which is of type List<object> called activity
        // In my xaml I just want to be outputting the 1st entry of the List<object> property .created_by_name
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler tempEvent = PropertyChanged;

        if (tempEvent != null)
        {
            // property changed
            tempEvent(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public IEnumerable<JamesStream> ActivityStream
    {
        get
        {
            return activityStream;
        }
        set
        {
            if (activityStream != value)
            {
                OnPropertyChanged();
            }
        }
    }

【问题讨论】:

  • 当然。它没有用。 :) 应该这样吗?
  • 我很困惑。你在哪里声明activity 改变了?当您的 xaml 没有引用它时,为什么所有这些关于 ActivityStream 的代码?
  • ActivityStream 充满了 API 调用的内容......我的 ActivityStream 数据合约处理返回的所有位和 bobs(并且该类来自 json 到 c# 工具)。 ActivityStream是一个ListBox绑定,上面是ActivityStream子属性的数据模板;其中之一是活动。希望对你有帮助

标签: c# xaml windows-phone-8


【解决方案1】:

如果您的 IEnumerable 具有 .First 属性,您可以附加到该属性吗?

【讨论】:

  • 这是我需要自己编码的东西吗?那么向仅表示第一个元素的活动添加一个附加属性?实际上只是尝试过。首先,它似乎没有用。
【解决方案2】:

您的代码可以正常工作...正常 :)。

你能展示一下你是如何填充你的收藏的吗?我认为这可能是因为您没有触发 INotifyPropertyChanged(或 INotify-like for collection)事件

【讨论】:

  • 更改 ObservableCollection 或在构造函数中加载您的活动列表(不是一个好习惯)。实际上,您的绑定不会收到有关您的集合更改的通知。
  • 这都是因为它是一个“对象”而不是一个预定义的类吗?
  • 在 WPF 中有效,但在 WP 或 WinRT 上...有时很奇怪,所以可以。
  • 事实上,只是出于测试目的,我准备了一个数据模板,果然属性不起作用。所以是的,事实上我没有明确定义这个类,只是把它作为类型对象,这意味着它不工作 arghhh ......它们有不同的类型。我将不得不在我猜想的集合上做一个开关,并在活动属性上做一个变体类型 T 或其他东西:S。这会伤害我的。
  • 或者您可以实现一个描述要绑定的值的通用接口。或者使用转换器,您绑定您的对象,然后转换器选择要返回的正确转换/值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
相关资源
最近更新 更多