【问题标题】:Binding custom class to listbox from custom class将自定义类从自定义类绑定到列表框
【发布时间】:2012-01-25 13:56:30
【问题描述】:

我有这些课程:

public class MovieExt
{
        public string Title { get; set; }
        public string Year { get; set; }
        public List<string> Genres { get; set; }
        public List<Actor> Actors { get; set; }
        ....
}

public class Actor
{
    public string Name { get; set; }
    public string Birth { get; set; }
    public string Biography { get; set; }
    public string Url { get; set; }

}

这是我在我的页面中的方法:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{

    object obj;
    if (PhoneApplicationService.Current.State.TryGetValue("movie", out obj))
    {
        MovieExt movie = (MovieExt)obj;
        this.DataContext = movie;
        this.imgPoster.Source = new BitmapImage(new Uri(movie.PosterUrl, UriKind.Absolute));
    }
    base.OnNavigatedTo(e);
}

在页面中我正在绑定这样的属性:

<ListBox Grid.Row="4" Grid.Column="1" 
                             Margin="5,5,5,5"
                             ItemsSource="{Binding Path=Actors }"
                             x:Name="listStars"/>

适用于所有工作(流派和其他)。其他一切都是字符串。但是对于我想绑定列表名称的演员,点击演员后我想去 url。如何绑定演员的名称属性?谢谢

【问题讨论】:

    标签: windows-phone-7 data-binding binding windows-phone-7.1


    【解决方案1】:

    首先,您需要在您的ListBox 上创建OnSelectedItemChanged 事件来处理您的Actors 上的点击。

    然后你需要得到你点击的项目。您可以通过多种方式做到这一点。最简单的方法是listBox.SelectedItem 属性。

    然后您可以通过(listBox.SelectedItem as Actor).Url 获取您的网址

    此外,当您从详细信息页面返回时,SelectedItem 将不为空,并在第二次单击同一项目未触发事件。所以,在处理点击时将SelectedItem设置为null

    UPD:要将Actor 类正确绑定到ListBox,您需要创建ItemTemplate

     <ListBox ...>
          <ListBox.ItemTemplate>
               <DataTemplate>
                    <StackPanel>
                         <TextBlock Text={Binding Name} />
                         <TextBlock Text={Binding Birth} />
                         <TextBlock Text={Binding Biography} />
                         <TextBlock Text={Binding Url} />
                    </StackPanel>
               </DataTemplate>
          </ListBox.ItemTemplate>
     </ListBox>
    

    【讨论】:

    • 它用于手柄点击,非常棒,谢谢。但这不是我的问题。我想在列表框中显示演员类的名称属性,但现在我有了“namespace.Actor”。
    • 我更新了答案。如果它解决了您的问题,请将其标记为答案。
    【解决方案2】:

    您可以覆盖 Actor 类中的 ToString() 方法以显示友好的内容,例如名称。

        public override string ToString()
        {
            return Name;
        }
    

    这在将对象绑定到组合框和下拉列表时很有用。

    【讨论】:

    • 为什么会被降级?需要详细说明吗?
    • 不是我做的,我认为你的回答很聪明,但我想我会使用 itemtemplate。
    • 我会使用 ItemTemplate 并且它更通用,但很多时候我发现自己只需要更改项目文本的显示方式,并且在这些情况下覆盖 ToString 是要走的路,这就是我建议它的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2012-03-10
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多