這是XAML代碼:
<ListBox ItemsSource="{Binding MyList}" SelectionMode="Multiple" Width="200">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="2">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding IsSelected}"/>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" Background="Transparent"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
而其背後的代碼:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
for (int i = 0; i < 100; i++)
{
MyList.Add(new ViewModel());
}
}
//MyList Observable Collection
public ObservableCollection<ViewModel> MyList { get { return _myList; } }
private ObservableCollection<ViewModel> _myList = new ObservableCollection<ViewModel>();
}
ViewModel類(每個項目):
public class ViewModel : DependencyObject
{
//Text Dependency Property
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ViewModel),
new UIPropertyMetadata(null, (d, e) =>
{
((ViewModel)d).IsSelected = !string.IsNullOrWhiteSpace((string)e.NewValue);
}));
//IsSelected Dependency Property
public bool IsSelected
{
get { return (bool)GetValue(IsSelectedProperty); }
set { SetValue(IsSelectedProperty, value); }
}
public static readonly DependencyProperty IsSelectedProperty =
DependencyProperty.Register("IsSelected", typeof(bool), typeof(ViewModel),
new UIPropertyMetadata(false, (d, e) =>
{
}));
}
我已成功這一點,但它只是我的問題的一半。 – Nadavrbn