绑定自定义类从自定义类
列表框我有这些类:绑定自定义类从自定义类
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。我怎样才能绑定来自actor的名称属性?谢谢
首先,您需要在您的ListBox
上创建OnSelectedItemChanged
事件来处理您的Actors
的点击。
然后你需要得到你点击的项目。你可以用几种方法来做到这一点。最简单的方法是listBox.SelectedItem
属性。
然后你可以用(listBox.SelectedItem as Actor).Url
而且,当你去从细节页面返回,SelectedItem
将不为空,然后单击同一项目中第二次不触发事件得到您的网址。因此,设置SelectedItem
当点击的处理
UPD为null:正确绑定Actor
类,你需要创建ItemTemplate
ListBox
:
<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>
您可以覆盖在演员类的ToString()
方法来显示一些友善的东西,如名字。
public override string ToString()
{
return Name;
}
当将对象绑定到组合框和下拉列表时,这非常有用。
这是为什么被低估?谨慎阐述? – 2011-12-22 00:13:07
这不是我的,我认为你的答案很聪明,但我想我会使用itemtemplate。 – 2011-12-22 08:11:03
我会使用ItemTemplate以及它更通用,但是很多时候我发现自己只需要改变项目文本的显示方式,重写ToString就是在这些情况下去的方式,这就是我为什么要这么做的原因。 – 2011-12-22 13:49:30
这是为处理咔嗒声,它是伟大的,thansk为此。但这不是我的问题。我想从列表框中的演员类显示名称属性,但现在我有“namespace.Actor”。 – 2011-12-21 19:53:05
我更新了答案。如果它解决了您的问题,请将其标记为答案。 – Ku6opr 2011-12-22 08:03:40