取消将新行添加到datagrid

时间:2013-12-05 06:09:54

标签: c# wpf datagrid combobox wpftoolkit

我有Datagrid,我使用Observable Collection作为我的datagrid的数据源。我从组合框的选定值填充我的Datagrid。组合框只有2个值:Direct Bill和PO Bill。如果用户从组合框中选择Direct bill,那么用户可以向datagrid添加行。如果值为PO Bill,则用户无法向datagrid添加行。

但我的问题是,如果组合框值为PO Bill,我想取消向数据网格添加新行。我已经使用CollectionChangedEvent尝试了它,但是如何实现这个目的却失败了?

我的代码背后是:

 void ListCollectionChanged
               (object sender, 
               System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {

        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            return;
        }

    }

1 个答案:

答案 0 :(得分:1)

由于您尚未发布任何相关代码,因此这不是一个完整的答案,但我希望这会引导您走上正确的道路。

我不知道你在哪里添加一行,但是你可以用这种方式影响这样做的能力:

CS:

public enum EBillType
{
    Direct , PO
};


public class BillTypeToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {           
        EBillType billType = (EBillType)value;
        return billType == EBillType.PO;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

xaml:

<Window.Resources>  
    <ObjectDataProvider x:Key="billTypes" MethodName="GetValues" 
                ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:EBillType" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

    <local:BillTypeToBooleanConverter x:Key="billTypeToBooleanConverter" />        
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="4*"/>
    </Grid.RowDefinitions>

    <ComboBox x:Name="cb" ItemsSource="{Binding Source={StaticResource billTypes}}" IsSynchronizedWithCurrentItem="True"/>
    <DataGrid 
            AutoGenerateColumns="False"
            ItemsSource="{Binding Bills}"
            CanUserAddRows="{Binding ElementName=cb, Path=SelectedValue, 
                  Converter={StaticResource billTypeToBooleanConverter}, Mode=OneWay}" Grid.Row="1" />                                                                            
</Grid>