如果ItemSsource Binding没有返回数据,则向DataGrid添加Row

时间:2013-01-28 16:09:25

标签: wpf xaml

这个问题是否有任何简单的解决方案..首先我认为我可以创建一个空的ObservableCollection和writte:

ObservableCollection<PersonDetailsView> newOCollection= new ObservableCollection<PersonDetailsView>();
myDataGrid.ItemsSource=newOCollection.ToArray();

它工作..我得到一个空行..但问题是我松开了另一个绑定..只有当我的{Binding Person}(见代码)没有时才有任何方法绑定到newOCollection t返回一个值

<DataGrid CanUserAddRows="True" IsReadOnly="False" BorderBrush="#FFCCCCCC"  
        GridLinesVisibility="All" AutoGenerateColumns="False" 
        ItemsSource="{Binding Person}" Background="White" Margin="10,45,0,0" 
        VerticalAlignment="Top" Height="91" HorizontalAlignment="Left" 
        HeadersVisibility="None" SelectionMode="Single" Name="dtaPersons" Width="415">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Person.Name, Mode=TwoWay}" Width="Auto"/>
        <DataGridTextColumn Binding="{Binding Person.Surname, Mode=TwoWay}" Width="*"/>
        <DataGridTemplateColumn Width="Auto">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate >
                    <Button  Style="{DynamicResource ChromelessButtonStyle}" Content="r" FontFamily="Marlett" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
   </DataGrid.Columns>
</DataGrid>

1 个答案:

答案 0 :(得分:0)

ObservableCollection<PersonDetailsView> newOCollection= new ObservableCollection<PersonDetailsView>();

if (!myDataGrid.Items.Any())
    myDataGrid.ItemsSource=newOCollection.ToArray();