Windows Universal Listbox Items Acess Specific UI Element

旧时模样 提交于 2019-12-11 04:57:34

问题


Here is the xaml code of my ListBox:

<ListBox x:Name="BoardList"  >
     <ListBox.ItemTemplate>
         <DataTemplate>
              <Grid>
                 <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                     <TextBox IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Visible" Text="{Binding}" TextWrapping="Wrap" Foreground="DarkBlue"></TextBox>
                     <AppBarButton Visibility="Collapsed" Icon="Globe" Click="OpenInBrowser" x:Name="Link"></AppBarButton>
                     <AppBarButton Icon="Copy" Click="Copy"></AppBarButton>
                     <AppBarButton Icon="Delete" Click="Delete"></AppBarButton>
                 </StackPanel>
              </Grid>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The ItemSource gets binded to a simple list of strings which is called notes. Now I check if the note begins with http and if it does the AppBarButton "link" for this specific item should be Visible. How do I achieve that? I already wrote the loop.

for (int i = 0; i < notes.Count; i++)
{
     if (notes[i].StartsWith("http"))
     {

     }
}

回答1:


Create a class with text and visibility as properties:

public class CustomObject
{
    public CustomObject(string text)
    {
        this.text = text;
    }
    public string text { get; set; }
    public Visibility visibility
    {
        get
        {
            if (text.StartsWith("http"))
                return Visibility.Visible;
            else
                return Visibility.Collapsed;
        }
    }
}

Set your ItemsSource to a list of CustomObjects.

Set your Bindings to text and visibility respectively in the xaml file:

<ListBox x:Name="BoardList"  >
 <ListBox.ItemTemplate>
     <DataTemplate>
          <Grid>
             <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                 <TextBox IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Visible" Text="{Binding text}" TextWrapping="Wrap" Foreground="DarkBlue"></TextBox>
                 <AppBarButton Visibility="{Binding visibility}" Icon="Globe" Click="OpenInBrowser"></AppBarButton>
                 <AppBarButton Icon="Copy" Click="Copy"></AppBarButton>
                 <AppBarButton Icon="Delete" Click="Delete"></AppBarButton>
             </StackPanel>
          </Grid>
     </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>


来源:https://stackoverflow.com/questions/32118282/windows-universal-listbox-items-acess-specific-ui-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!