我是Caliburn Micro的新手,他试图通过将DataGrid作为参数传递给命令来将DataGrid导出为excel
传递给方法的参数始终为null 所以我得到空异常
这是XAML代码:
<DataGrid x:Name="grdPeople" ItemsSource="{Binding Path=People}"/>
<Button cal:Message.Attach="[Event Click] = [Action btnExportToExcel(grdPeople)]" />
我的ViewModel:
public class ShellViewModel : PropertyChangedBase
{
private ObservableCollection<Person> people;
public ObservableCollection<Person> People
{
get { return people; }
set
{
people = value;
NotifyOfPropertyChange(() => People);
}
}
public ShellViewModel()
{
People = new ObservableCollection<Person>();
people.Add(new Person { FirstName = "Zico", LastName = "Ayoub" });
people.Add(new Person { FirstName = "Fibi", LastName = "Victor" });
people.Add(new Person { FirstName = "Matthew", LastName = "Zakaria" });
people.Add(new Person { FirstName = "Marco", LastName = "Zakaria" });
}
public void btnExportToExcel(DataGrid dg)
{
string fileName = @"d:\myfile.csv";
dg.SelectAllCells(); // Error Here (Object reference not set to an instance of an object)
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dg);
String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result = (string)Clipboard.GetData(DataFormats.Text);
dg.UnselectAllCells();
System.IO.StreamWriter file1 = new System.IO.StreamWriter(fileName);
file1.WriteLine(result);
file1.Close();
}
}
我希望传递DataGrid的实例,但是我得到了空的DataGrid
答案 0 :(得分:1)
如果您确实希望将对元素的引用传递给视图模型,则可以使用长语法:
<Button xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="btnExportToExcel">
<cal:Parameter Value="{Binding ElementName=grdPeople}" />
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
但是,如果您遵循MVVM设计模式,则视图模型不应引用DataGrid
。