下午好,我正在尝试获取DataGrid中选定行的列表,但是SelectedItem只返回一个选定行,而不是它们的列表=[
我在WPF项目中使用Caliburn Micro进行MVVM。
---这是我的数据网格--
<DataGrid Margin="5" AutoGenerateColumns="False" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
CanUserAddRows="False" SelectionMode="Extended" MinHeight="320"
SelectedItem="{Binding Path=SelectedRows, Mode=OneWayToSource}" x:Name="Avisos" SelectionUnit="FullRow">
<DataGrid.Columns>
<DataGridTextColumn Header="Inquilino" Binding="{Binding Inquilino}" MinWidth="150"/>
<DataGridTextColumn Header="Propietário" Binding="{Binding Propietario}" MinWidth="150"/>
<DataGridTextColumn Header="Imovel" Binding="{Binding Imovel}" MinWidth="150"/>
<DataGridTextColumn Header="Data Aviso" Binding="{Binding DataLembrete}" MinWidth="150"/>
<DataGridTextColumn Header="Status" Binding="{Binding Status}" MinWidth="70"/>
<DataGridTextColumn Header="Descrição" Binding="{Binding Descrição}" MinWidth="150" Width="*"/>
</DataGrid.Columns>
<DataGrid>
---这是我在ViewModel上的列表---
public ObservableCollection<AvisoModel> SelectedRows { get; set; }
---我收到这个错误---
Exceção gerada:'System.NotSupportedException'em PresentationFramework.dllSystem.Windows.Data错误:7:ConvertBack无法转换值"MiniAgentdaTay.Models.AvisoModel"(类型为"AvisoModel"(。BindingExpression:Path=SelectedRows;DataItem="MainWindowViewModel"(哈希代码=10588721(;目标元素是"DataGrid"(名称="Visos"(;目标属性为"SelectedItem"(类型为"Object"(NotSupportedException:"System.NotSupportedException:CollectionConverter无法从MiniAgentdaTay.Models.VisoModel转换。位于MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o,Type destinationType,DependencyObject targetElement,CultureInfo区域性,Boolean isForward(位于MS.Internal.Data.ObjectTargetConverter.ConvertBack(对象o,类型类型,对象参数,CultureInfo区域性(位于System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter转换器,Object值,Type sourceType,Object参数,CultureInfo区域性('
您可以定义为Behavior,它使用DataGrid的SelectedItems属性。SelectedItems不是DepedencyProperty,这就是为什么您不能立即执行此操作的原因。
public class DataGridSelectedItemsBehavior:Behavior<DataGrid>
{
protected override void OnAttached()
{
AssociatedObject.SelectionChanged += SelectionChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= SelectionChanged;
}
void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItems = AssociatedObject.SelectedItems;
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register(nameof(SelectedItems), typeof(IEnumerable), typeof(DataGridSelectedItemsBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public IList SelectedItems
{
get { return (IList)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
}
现在您可以将Xaml中的行为添加为
<i:Interaction.Behaviors>
<behaviors:DataGridSelectedItemsBehavior SelectedItems="{Binding SelectedItems, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
在您的ViewModel 中
public IEnumerable<object> SelectedItems { get; set; }