问题
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