我有:
public class Extra
{
public string Name {get;set;}
}
我有
public class CarViewModel
{
public ObservableCollection<Extra> OwningExtras { get; set; }
public static IEnumerable<Extra> AllExtras
{
get
{
return Extra.GetAllExtras();
}
}
public CarViewModel()
{
owningExtras=Extra.GetAvailableExtrasForCar(idCar)
}
}
和CarView看起来像:
<Grid >
<ListBox ItemsSource="{Binding}" Name="lbExtras">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox"/> //How implement adding and removing Extras
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
我想知道连接到this.DataContext的是什么?然后如何注意到某些事情发生了变化(Checked复选框意味着这辆车有额外的功能)
答案 0 :(得分:1)
下面的代码将显示列表框中AllExtras集合中的所有项目,并使用已检查的项目填充集合CheckedExtras。这只是解决这个问题的众多方法之一。不确定你的意思是“如何注意到某些事情发生了变化”。您是否需要获得有关已检查项目的集合更新的通知?在这种情况下,您可以使用ObservableCollection并监听其CollectionChanged事件。
XAML:
<Window x:Class="ListBoxTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<StackPanel>
<ListBox ItemsSource="{Binding Path=AllExtras}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Click="OnCheckBoxClick" />
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
代码背后:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace ListBoxTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new VM();
}
private void OnCheckBoxClick(object sender, RoutedEventArgs e)
{
VM vm = DataContext as VM;
CheckBox checkBox = sender as CheckBox;
Extra extra = checkBox.DataContext as Extra;
if (checkBox.IsChecked.GetValueOrDefault())
{
vm.CheckedExtras.Add(extra);
}
else
{
vm.CheckedExtras.Remove(extra);
}
}
}
public class VM
{
public VM()
{
CheckedExtras = new List<Extra>();
AllExtras = new List<Extra>() { new Extra() { Name = "A" }, new Extra() { Name = "B" }, new Extra() { Name = "C" }, };
}
public List<Extra> CheckedExtras { get; private set; }
public List<Extra> AllExtras { get; private set; }
}
public class Extra
{
public string Name { get; set; }
}
}