//xaml
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Serialize Binary"
Command="{Binding BinSerializeCmd}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>
</ContextMenu>
</DataGrid.ContextMenu>
// cs
private void BinSerializeCmdExecuted(object obj)
{
var dg = obj as DataGrid;
if(dg!=null)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "All Files|*.*|Bin Files|*.bin";
dialog.FileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.bin";
if(dialog.ShowDialog()==true)
{
using(System.IO.FileStream fs=new System.IO.FileStream(dialog.FileName,System.IO.FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(fs,dg.Items.Cast<Book>().ToList());
MessageBox.Show($"Saved in {dialog.FileName}", "Binary Formatter Serialize", MessageBoxButton.OK);
}
}
}
}
![]()
![]()