8,735
社区成员
发帖
与我相关
我的任务
分享
// xaml
<ListBox Name="ItemsToBuy" ItemsSource="{Binding ItemsFromRecipe}" /> // 显示某个菜单中的原料,这部分显示正常
<Button Name="AddButton" Content="Add To List" Grid.Row="3" Click="AddButton_Click"/> // 想在点击这个按钮时把原料加入下面的 ListBox。
<ListBox Name="ShopListBox" ItemsSource="{Binding ItemsToBuy}" Grid.Column="1" ScrollViewer.VerticalScrollBarVisibility="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Name="ItemName" Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public partial class MainWindow : Window
{
ShopList shopList = new ShopList();
public MainWindow()
{
InitializeComponent();
ShopListBox.DataContext = shopList;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
shopList.AddToList(recipeItems.ItemsFromRecipe); // recipeItems.ItemsFromRecipe 的代码就不贴了,可以确保这部分没问题,在 debugger 里看,是正常返回了一个 List<string> 的
}
}
}
public class ShopList : INotifyPropertyChanged
{
private List<string> itemsToBuy;
public List<string> ItemsToBuy // ShopListBox 绑的就是这个属性
{
get { return itemsToBuy; }
}
public event PropertyChangedEventHandler PropertyChanged;
public void AddToList(List<string>items)
{
var tempList = itemsToBuy==null?new List<string>():itemsToBuy;
foreach (var item in items)
{
if (!tempList.Contains(item))
{
tempList.Add(item);
};
}
itemsToBuy = tempList;
OnPropertyChanged(nameof(itemsToBuy));
}
private void OnPropertyChanged([CallerMemberName]string callProperty = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(callProperty));
}
}
}