所以我所做的就是制作我自己的自定义ListBoxItemTemplate。它由3个Textblocks和1个Button组成。我的XAML就是:
<DataTemplate x:Key="DataTemplate1">
<Grid d:DesignWidth="431" d:DesignHeight="109.333" Height="109.333" Width="431">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsFadeEnabled="True" IsZoomEnabled="False">
<toolkit:MenuItem Header="Delete" Click="Delete_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Grid toolkit:TiltEffect.IsTiltEnabled="True" Margin="101,-1,-121,-3">
<TextBlock Text="{Binding ItemBody}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26" Width="496" FontSize="19" Margin="0,62,0,0" FontFamily="Segoe WP">
<TextBlock.Foreground>
<SolidColorBrush Color="{StaticResource PhoneTextMidContrastColor}"/>
</TextBlock.Foreground>
</TextBlock>
<TextBlock Text="{Binding FolderID}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Height="34" Width="496" FontSize="24" Margin="0,72,0,0" Visibility="Collapsed"/>
<TextBlock Text="{Binding ItemNumber}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="28" Width="496" FontSize="21" Margin="0,34,0,0" FontFamily="Segoe WP"/>
<TextBlock Text="{Binding ItemTitle}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="37" Width="496" FontSize="28" FontFamily="Segoe WP"/>
</Grid>
<Button x:Name="callPerson" Content="CALL" HorizontalAlignment="Left" Margin="-6,12,0,0" VerticalAlignment="Top" Click="callPerson_Click"/>
</Grid>
</DataTemplate>
我已经绑定了3个TextBlocks,我刚刚添加了一个按钮。现在我打算做的是每次用户点击按钮,关闭它是什么列表框项目,一旦点击按钮,它将从Observable Collection中获取一个数字,我已经在一个名为Collections的不同类文件中添加了该数字。 CS。代码是:
public class Items
{
public string ItemTitle { get; set; }
public string ItemBody { get; set; }
public string FolderID { get; set; }
public string ItemNumber { get; set; }
}
现在在我的MainPage中,当单击该按钮时,它意味着抓取ItemNumber。代码是:
Collections.Items data = (Collections.Items)listBox.SelectedItem;
PhoneCallTask call = new PhoneCallTask();
call.DisplayName = data.ItemTitle;
call.PhoneNumber = data.ItemNumber;
call.Show();
所以这意味着抓住这个数字然后召唤它但是!问题是,如果我单击按钮而不首先单击ListboxItem,它将抛出一个null异常。我怎样才能使它不需要先点击ListBoxItem,而只需点击按钮就可以获取数字?
谢谢!
答案 0 :(得分:1)
将我的评论转换为答案,以便其他人可以轻松发现,因为OP确认它是有效的解决方案。
我们可以从Button Collections.Items
中点击与Button相对应的DataContext
。按钮单击事件处理程序中的类似内容:
Collections.Items data = (Collections.Items)((Button)sender).DataContext;
答案 1 :(得分:0)
我宁愿使用itemscontrol而不是列表框。列表框是一个易于使用和覆盖的模板,但是对于选择事件处理程序,它有时会在创建自定义类型控件时阻碍性能。尝试将列表框更改为itemscontrol:
<ItemsControl ItemSource={binding mycollection}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- Your dataTemplate code here -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>