在我的Windows Phone应用程序中,从JSON(webservice)填充ListBox。
如果字符串等于ListBox上的某个项,我需要测试。但我"绑定"许多信息,我只想用{Binding codigo}
进行测试。
此代码对我不起作用:
private void addProduto(object sender, RoutedEventArgs e)
{
Fields fi = (Fields)this.List1.SelectedItem as Fields;
foreach(var item in List1.Items)
{
Fields fields = item as Fields;
if (fields.codigo == insCodProduto.Text)
{
MessageBox.Show("Esse produto existe!");
}
else
{
MessageBox.Show("Esse produto não existe!");
break;
}
}
我的代码:
public ObservableCollection<Fields> Items { get; set; }
public class Fields
{
//[JsonProperty(PropertyName = "descricao")]
public string descricao { get; set; }
public double valor_preco_a { get; set; }
public string codigo { get; set; }
public string codigo1 { get; set; }
}
XAML:
<ListBox Name="List1" ItemsSource="{Binding Items}" Margin="0,85,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="242" />
<ColumnDefinition Width="128" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Margin="0,0,-62,17" Grid.ColumnSpan="3">
<StackPanel.Background>
<SolidColorBrush Color="#FF858585" Opacity="0.5"/>
</StackPanel.Background>
<TextBlock x:Name="NameTxt" Grid.Column="0" Text="{Binding descricao}" TextWrapping="Wrap" FontSize="20" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Grid.Column="1" Text="{Binding valor_preco_a, StringFormat=N2}" TextWrapping="Wrap" Margin="45,20,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Grid.Column="3" Text="{Binding codigo}" TextWrapping="Wrap" FontSize="35" Margin="370,-50,12,0" Style="{StaticResource PhoneTextNormalStyle}" Foreground="Blue"/>
</StackPanel>
<TextBlock Grid.Column="0" Text="R$" Margin="15,48,158,17" Style="{StaticResource PhoneTextSubtleStyle}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
insCodProduto:
<TextBox InputScope="Number" x:Name="insCodProduto" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="161" TextAlignment="Center" Margin="262,152,0,0" Height="78"/>
答案 0 :(得分:1)
首先将您的项目投放到Fields
课程。现在您可以访问
Fields fields = item as Fields;
if (fields.descricao == insCodProduto.Text)
{
//do your stuff
}
答案 1 :(得分:1)
您需要投射每个List Item
以从中获取特定值:
foreach(Fields item in List1.Items) //casting listbox item to "Fields"
{
if(item.codigo.ToString() == insCodProduto.Text) //codigo is int type so you'll have to convert it to string
{
MessageBox.Show("ok");
}
}