我有以下代码:
<ListView SelectionMode="Multiple" ItemsSource="{Binding MyList}" ItemTemplate="{StaticResource MyListTemplate}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
使用以下DataTemplate:
<Page.Resources>
<!-- Data Template for the ListView -->
<DataTemplate x:Key="MyListTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding Path=Icon}" />
<StackPanel Grid.Column="1" Orientation="Vertical">
<TextBlock Text="{Binding Path=EntryDate}" TextAlignment="Left" />
<TextBlock Text="{Binding Path=Url}" TextAlignment="Left" />
<TextBlock Text="{Binding Path=Text}" TextAlignment="Left" />
</StackPanel>
</Grid>
</DataTemplate>
</Page.Resources>
在我的ViewModel中,我有以下内容:
private ObservableCollection<MyModel> myList;
public ObservableCollection<MyModel> MyList {
get { return myList; }
set {
myList = value;
RaisePropertyChanged("MyList");
}
}
public IEnumerable<MyModel> SelectedItems {
get { return MyList == null ? null : MyList.Where(e => e.IsSelected); }
}
在我的模型中,我拥有以下IsSelected
财产:
private bool isSelected;
public bool IsSelected {
get { return isSelected; }
set { Set(ref isSelected, value); }
}
我可以看到SelectedItems
元素具有所有元素MyList
,但是,当我在UI中选择一些元素时,该属性IsSelected
未更新,它们都保留为false。
那我在做什么错呢?
感谢MSDN论坛中的YossiStarz,我设法解决了我的问题。所以这是他的解决方案:
问题是您不能在放置样式的元素上使用样式来对SetBinding进行设置。这是因为样式是在创建列表视图时创建的,而不是为每个项目容器创建的。实际上,您正在创建一个样式对象,该对象具有一个setter对象,该对象的Value属性绑定到Style父对象的DataContext的IsSelected(没有巫婆)。发生此绑定是为了在设置器中设置Value属性的值。如果它将成功获取价值,那么这就是它将为所有项目容器设置的价值。
我为您提供解决方案。
首先也是最简单的,创建以下帮助程序类:
public class Helper {
public static string GetIsSelectedContainerBinding(DependencyObject obj) {
return (string)obj.GetValue(IsSelectedContainerBindingProperty);
}
public static void SetIsSelectedContainerBinding(DependencyObject obj, string value) {
obj.SetValue(IsSelectedContainerBindingProperty, value);
}
// Using a DependencyProperty as the backing store for IsSelectedContainerBinding. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsSelectedContainerBindingProperty =
DependencyProperty.RegisterAttached("IsSelectedContainerBinding", typeof(string), typeof(helper), new PropertyMetadata(null, IsSelectedContainerBindingPropertyChangedCallback));
public static void IsSelectedContainerBindingPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) {
BindingOperations.SetBinding(d, ListViewItem.IsSelectedProperty, new Binding() {
Source = d,
Path = new PropertyPath("Content." + e.NewValue),
Mode = BindingMode.TwoWay
});
}
}
现在将设置器更改为:
<Style TargetType="ListViewItem">
<Setter Property="local:Helper.IsSelectedContainerBinding" Value="IsSelected"/>
</Style>
这应该将SetBinding应用于创建的每个容器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句