【发布时间】:2012-04-09 05:58:32
【问题描述】:
我有这个使用 Microsoft Expression Blend 创建的自定义列表框,其中包含三个项目(图像、名称和文本)。这是列表框模板的代码!!
<DataTemplate x:Key="ListBoxTemplate">
<Grid Width="320" Height="80" Background="#FFCAE5DE">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Path Grid.ColumnSpan="1" Data="M8.4999981,6.8212103E-13 L256.5,6.8212103E-13 C261.19443,-1.8775456E-06 265,3.8055778 265,8.4999981 L265,55.499998 C265,60.194418 261.19443,63.999998 256.5,63.999998 L52.689537,63.999998 52.702888,75.988852 45.902157,63.999998 8.4999981,63.999998 C3.8055797,63.999998 0,60.194418 0,55.499998 L0,8.4999981 C0,3.8055778 3.8055797,-1.8775456E-06 8.4999981,6.8212103E-13 z"
Fill="#FF3E977D" Height="Auto" Margin="5,5,8,-11" StrokeStartLineCap="Round" Stretch="Fill" StrokeEndLineCap="Round" StrokeDashCap="Round" Stroke="Black" StrokeThickness="0"
StrokeLineJoin="Round" VerticalAlignment="Stretch" Grid.Column="1" Opacity="0.535" />
<Border Margin="10,5,0,-2" BorderBrush="Black" BorderThickness="1" Height="Auto" CornerRadius="4">
<Image Source="{Binding Path=ImageURL}" Stretch="Fill" Width="Auto" Height="Auto" />
</Border>
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" Height="Auto" Width="Auto" Grid.Column="1" Margin="5,5,0,-11">
<TextBlock Text="{Binding Path=Text}" Width="400" Margin="3,2,0,16" Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" TextAlignment="Justify" TextWrapping="Wrap" ScrollViewer.HorizontalScrollBarVisibility="Auto"/>
</StackPanel>
<StackPanel Margin="0,47,43.5,-51" Grid.Column="1" Height="Auto" HorizontalAlignment="Stretch" Width="Auto" Grid.Row="1">
<TextBlock Text="{Binding Path=Name}" Height="20" Margin="60,20,8,0" Width="Auto"/>
</StackPanel>
</Grid>
</DataTemplate>
如您所见,我有三个绑定(ImageURL、文本和名称)。现在要做的是在 C# 中实现一个允许我在此列表框中添加新项目的方法。作为开始,我找到了一些使用 c# 添加 lisboxitem 的示例,但我不知道如何将它应用到我的自定义列表框...... c# 中的方法是这样的!
private ListBoxItem AddItem(string imageUrl, string text, string name)
{
ListBoxItem item = new ListBoxItem();
/* the
code
of
the
customized
ListBox */
item.content = content;
return item;
}
问题是,当我调用 AddItem(imageUrl, text, name) 方法时,如何在自定义列表框中添加新项目?
任何想法.. 任何帮助都将不胜感激。
@Margnus Johnansson 非常感谢您提供的解决方案。 但是还有一个问题..如果我想添加多个项目怎么办?我该怎么办?! 这是我实现的方法..
public void Additem(string imageUrl, string text, string name)
{
ObservableCollection<Person> Items = new ObservableCollection<Person>();
MyListBox.ItemsSource = Items;
Items.Add(new Person() { Image = imageUrl, Text = text, Names = name });
}
即使我多次调用此方法,它也只会添加一个项目,但我的问题是每次调用该方法时我都想在列表框中添加一个新项目
Additem(string imageUrl, string, text, string name)
不覆盖其他项目!!
感谢理解。
【问题讨论】:
-
您不应该在 Add 方法中创建 ObservableCollection。例如,将该全局放在构造函数中的 Page/Window 中。这就是您看到您描述的问题的原因,因为您将在每次添加项目时重置并清除它。当您使用它时,还将分配 MyListBox.ItemsSource 也移动到外部(例如在您的构造函数或页面加载中)
-
感谢您,问题解决了!!
标签: c# listbox listboxitem