2013-03-19 2 views
1

У меня есть список элементов «SmartText», которые в основном связаны объектами со свойствами для названия, описания и URL-адреса. Я пытаюсь сделать панель Grid в XAML доступной, так что нажатие на всю сетку переходит к URL-адресу. Как мне получить доступ к свойству URL, чтобы я мог перейти к нему?Как получить доступ к свойству элемента в ListBox в XAML?

<controls:Pivot VerticalAlignment="Stretch" 
       HorizontalAlignment="Stretch" 
       Margin="0,0,0,0" 
       x:Name="PivotRoot" 
       Title="{Binding SmartTextStateModel.Title}" 
       SelectionChanged="Pivot_SelectionChanged" 
       Background="{StaticResource PhoneBackgroundBrush}"> 
    <controls:PivotItem Header="{Binding Path=Labels.SmartTextBingHeaderLabel, Source={StaticResource Translations}}" Tag="bingsearch"> 
     <ListBox ItemsSource="{Binding SmartTextStateModel.BingItemResults}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <Grid Tap="SmartTextElement_Tap"> 
         <Grid.RowDefinitions> 
          <RowDefinition Height="*"/> 
          <RowDefinition Height="Auto"/> 
          <RowDefinition Height="Auto"/> 
         </Grid.RowDefinitions> 
         <TextBlock Grid.Row="0" FontSize="40" Text="{Binding Path=Title}" /> 
         <TextBlock Grid.Row="1" TextWrapping="Wrap" FontSize="18.667" Foreground="{StaticResource PhoneDisabledBrush}" 
            TextTrimming="WordEllipsis" MaxHeight="100" Text="{Binding Path=Description}"/> 
         <TextBlock Grid.Row="2" Foreground="{StaticResource PhoneAccentBrush}" Text="{Binding Path=Url}"/> 
        </Grid> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </controls:PivotItem> 

    ... 

</controls:Pivot> 

и определение класса

public class SmartTextItemModel : BaseModel 
{ 
    private string _title; 
    private string _description; 
    private string _url; 

    /// <summary> 
    /// The title of the linked page (Large text) 
    /// </summary> 
    public string Title 
    { 
     get { return _title; } 
     set 
     { 
      if (_title != value) 
      { 
       _title = value; 
       NotifyPropertyChanged("Title"); 
      } 
     } 
    } 

    /// <summary> 
    /// Description of the page (smaller text) 
    /// </summary> 
    public string Description 
    { 
     get { return _description; } 
     set 
     { 
      if (_description != value) 
      { 
       _description = value; 
       NotifyPropertyChanged("Description"); 
      } 
     } 
    } 

    /// <summary> 
    /// Url of the page 
    /// </summary> 
    public string Url 
    { 
     get { return _url; } 
     set 
     { 
      if (_url != value) 
      { 
       _url = value; 
       NotifyPropertyChanged("Url"); 
      } 
     } 
    } 

    public SmartTextItemModel(string _t, string _d, string _u) 
    { 
     this._title = _t; 
     this._description = _d; 
     this._url = _u; 
    } 
} 

Конечно обработчик событий в файле .cs выглядит следующим образом:

private void SmartTextElement_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
{ 
    ... ? 
    // Navigate to url... 
} 

Примечание: Это был ближайший StackOverflow вопрос мой: How to get the listbox item's properties after event "tap", но это все равно не помогло.

+0

Я не понимаю вашего вопроса. У вас есть свойство URL в ViewModel. Просто достань оттуда. –

+0

Отправитель в обработчике событий является элементом панели сетки. Я попробовал несколько способов добраться до URL-адреса элемента из ссылки на панель Grid, но ничего не сработало. Каждый элемент в списке - это другая ссылка SmartText. – Flames

+0

Делает ли «Tap» также элемент Item в ListBox, вы можете просто привязать его к элементу SelectedItem и использовать его в своем обработчике –

ответ

2

Grid находится внутри ItemTemplate от ListBox. Это означает, что Grid.DataContext свойство будет экземпляром вашего SmartTextItemModel класса:

private void SmartTextElement_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
{ 
    var grid = sender as Grid; 
    if (grid == null) 
     return; 

    var item = grid.DataContext as SmartTextItemModel; 
    if (item == null) 
     return; 

    item.// Navigate to url... 
} 
+0

Спасибо, я не знал о свойстве DataContext. Я думал, что мне нужно получить доступ к дочернему элементу TextBlock, а затем получить URL-адрес. – Flames

Смежные вопросы