質問

I have Datagrid , I am using an Observable Collection as data-source of my datagrid. I am populating my Datagrid from the selected value of a combobox .The combobox has only 2 values: Direct Bill and PO Bill .If the User select Direct bill from the combobox then the user can add rows to the datagrid. If the value is PO Bill then user cannot add rows to datagrid.

But my problem is that I want to cancel the add new row to the datagrid if the combo-box value is PO Bill. I have tried it using the CollectionChangedEvent but failed how to accomplish this?

My code behind is:

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

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

    }
役に立ちましたか?

解決

This is not a complete answer since you have not posted any relevant code , but i hope this will lead you on the right path .

I don't know from where you are adding a row , but you can influence the ability to do so in this manner :

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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top