[英]Binding the IsSelectedProperty of a ListBox in WPF is not working. Need Help
我正在嘗試做一些腦筋急轉彎的簡單操作,但是,我無法使其正常工作。 我在列表框中顯示項目列表。 我在列表框中添加了復選框,以便用戶可以選擇多個項目。 但是,即使列表中綁定到ListBox的對象具有“ IsSelected”屬性,也不會被綁定。 我可以使用一些幫助,因為這使我發瘋。
<Style x:Key="CheckBoxListStyle" TargetType="{x:Type ListBox}">
<Setter Property="SelectionMode" Value="Multiple"></Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Margin" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<CheckBox Focusable="False"
IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}">
<ContentPresenter></ContentPresenter>
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
<ListBox
Style="{StaticResource CheckBoxListStyle}"
IsEnabled="{Binding Path=SpecificClients.Value, Mode=OneWay}"
ItemsSource="{Binding Path=SelectedClients}"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
ScrollViewer.VerticalScrollBarVisibility="Auto"
MaxHeight="95">
</ListBox>
在視圖模型中,我具有以下內容:
public IEnumerable<SelectedClientVM> SelectedClients
....
public class SelectedClientVM
{
public bool IsSelected { get; set; }
public Client Client { get; set; }
public override string ToString()
{
return Client.SearchText;
}
}
我認為您可以通過定義用於ListBox中每個項目的DataTemplate
來更好地實現。 DataTemplate
指定您要如何在ListBox中呈現單個數據(在您的情況下為Client
)。
這是我的XAML,用於簡單的DataTemplate。
<DataTemplate x:Key="clientTemplate" DataType="{x:Type local:Client}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding IsSelected}" />
<TextBlock Grid.Column="1" Text="{Binding Name}" Margin="5,0,0,0" />
</Grid>
</DataTemplate>
這是我在ListBox聲明中引用它的方式:
<ListBox ItemsSource="{Binding SelectedClients}"
VirtualizingStackPanel.IsVirtualizing="True"
ItemTemplate="{StaticResource clientTemplate}" />
其次,對於Grant的回答,您需要確保您的Client
類實現INotifyPropertyChanged
。 另外,您將要使用支持更改通知的集合公開“客戶端”列表。 我通常使用ObservableCollection<T>
。
這可能不是唯一的問題,但是如果要基於ViewModel更新視圖,則必須在IsSelected屬性上實現INotifyPropertyChanged (或執行類似工作的東西)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.