我已将“ DataGridSelectedItemsBehavior”行为添加到xaml:
<DataGrid x:Name="MessagesListView" Grid.Row="0" Style="{StaticResource BasicDataGridStyleWithAutoHeight}"
ItemsSource="{Binding Source={StaticResource MessagesView}}" AutoGenerateColumns="False"
GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler"
IsEnabled="{Binding IsBusy, Converter={StaticResource InvertBoolConverter}}" IsReadOnly="True"
SelectionMode="Extended">
<i:Interaction.Behaviors>
<behaviors:DataGridSelectedItemsBehavior SelectedItems="{Binding SelectedItems, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
这是DataGridSelectedItemsBehavior类,并且“ SelectedItems”属性可以正常工作。根据选择的内容,将填充此IEnumerable集合。
public class DataGridSelectedItemsBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
=> AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
protected override void OnDetaching()
=> AssociatedObject.SelectionChanged -= AssociatedObjectSelectionChanged;
private void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var array = new object[AssociatedObject.SelectedItems.Count];
AssociatedObject.SelectedItems.CopyTo(array, 0);
SelectedItems = array;
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(IEnumerable), typeof(DataGridSelectedItemsBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public IEnumerable SelectedItems
{
get => (IEnumerable)GetValue(SelectedItemsProperty);
set => SetValue(SelectedItemsProperty, value);
}
}
我想访问我的viewModel中的此属性以将所有选定的项目复制到剪贴板,但不知道如何正确执行此操作:
public class MessagesViewModel : DialogWindowViewModel, IMessagesViewModel
{
public ObservableCollection<IEnumerable> SelectedItems { get; set; } = new ObservableCollection<IEnumerable>();
public MessagesViewModel(ILoggingService loggingService, ILogger logger = null)
{
_logger = logger;
_loggingSvc = loggingService;
CopyCommand = new RelayCommand(async () => await CopyLog().ConfigureAwait(false));
}
public RelayCommand CopyCommand { get; }
private async Task CopyLog()
{
Clipboard.SetText(FormatForClipboard(SelectedItems));
}
FormatForClipboard()
{
...
}
}
谢谢您的回答。