2015-10-08 4 views
0

Я пытаюсь отфильтровать dataGrid, выбирая два значения из двух comboBoxes, но выбранные значения отправляют значение 0 в свойство.dataGrid фильтр из combobox не работает

var idShop = Магазин; равный нулю

var idSupplier = поставщик; равно нулю

ViewModel

public class ConsultInvoiceViewModel:ViewModelBase 
    { 
     public Context ctx = new tContext(); 

     private ICollectionView _dataGridCollection; 
     private string _filterString; 
     private ObservableCollection<Invoice> invoiceCollection = new ObservableCollection<Invoice>(); 


     public ConsultInvoiceViewModel() 
     { 
      DataGridCollection = CollectionViewSource.GetDefaultView(Get()); 
      //DataGridCollection.Filter = new Predicate<object>(Filter); 
     } 

     public ICollectionView DataGridCollection 
     { 
      get 
      { 
       return _dataGridCollection; 
      } 
      set 
      { 
       _dataGridCollection = value; 
       OnPropertyChanged("DataGridCollection"); } 
     } 


     private void FilterCollection() 
     { 
      if (_dataGridCollection != null) 
      { 
       _dataGridCollection.Refresh(); 
      } 
     } 




     private void Search() 
     { 
      var idShop = Shop; 
      var idSupplier = Supplier; 

      var inv = (from i in ctx.Invoices 
         where i.shop == idShop 
         && i.supplier == idSupplier 
         select i).SingleOrDefault(); 

      invoiceCollection.Clear(); 
      invoiceCollection.Add(inv); 
      FilterCollection(); 

     } 

     private ObservableCollection<Invoice> Get() 
     { 
      ctx.Invoices.ToList().ForEach(invoice => ctx.Invoices.Local.Add(invoice)); 
      invoiceCollection = ctx.Invoices.Local; 
      return invoiceCollection; 
     } 
     private void GetShop() 
     { 
      ctx.shops.ToList().ForEach(shop => ctx.shops.Local.Add(shop)); 
      SShop = ctx.shops.Local; 
     } 

     private void GetSupplier() 
     { 
      ctx.foodSuppliers.ToList().ForEach(supplier => ctx.foodSuppliers.Local.Add(supplier)); 
      FoodSupplier = ctx.foodSuppliers.Local; 
     } 

     private IList<foodSupplier> supplier; 

     public IList<foodSupplier> FoodSupplier 
     { 
      get 
      { 
       if (supplier == null) 
       GetSupplier(); 
       return supplier; 
      } 
      set 
      { 
       supplier = value; 
       OnPropertyChanged("FoodSupplier"); 
      } 
     } 

     private IList<shop> shop; 

     public IList<shop> SShop 
     { 
      get 
      { 
       if(shop == null) 
       GetShop(); 
       return shop; 
      } 
      set 
      { 
       shop = value; 
       OnPropertyChanged("SShop"); 
      } 
     } 

     private int _shop; 

     public int Shop 
     { 
      get 
      { 
       return _shop; 
      } 
      set 
      { 
       _shop = value; 
       OnPropertyChanged("Shop"); 
      } 
     } 

     private int _supplier; 

     public int Supplier 
     { 
      get 
      { 
       return _supplier; 
      } 
      set 
      { 
       _supplier = value; 
       OnPropertyChanged("Supplier"); 
      } 
     } 





     #region "Command" 

     private ICommand searchCommand; 


     public ICommand SearchCommand 
     { 
      get 
      { 
       return searchCommand ?? (searchCommand = new RelayCommand(p => this.Search(), p => this.CanSearch())); 
      } 
     } 

     private bool CanSearch() 
     { 
      if (Supplier != 0 && Shop != 0) 
       return true; 
      else 
       return false; 

     } 

     #endregion 
    } 

Посмотреть

<StackPanel Orientation="Horizontal"> 
       <Label Content="Shop"/> 
       <ComboBox Name="shopComboBox" 
          Margin="5" 
          ItemsSource="{Binding SShop}" 
          DisplayMemberPath="shop1" Width="73" 
          SelectedItem="{Binding Shop, Mode=OneWayToSource}" 
          SelectedValuePath="idshop" SelectionChanged="shopComboBox_SelectionChanged"/> 
       <Label Content="Supplier"/> 
       <ComboBox Name="supplierComboBox" 
          Margin="5" 
          ItemsSource="{Binding FoodSupplier}" 
          DisplayMemberPath="supplier" 
          SelectedItem="{Binding Supplier, Mode=OneWayToSource}" 
          SelectedValuePath="idfoodSupplier" 
          Width="71"/> 
       <Label Content="Shop"/> 
       <Button Content="Search" 
          Margin="5" 
          Command="{Binding SearchCommand}"/> 
      </StackPanel> 


      <StackPanel Orientation="Vertical"> 
       <DataGrid Margin="5" ItemsSource="{Binding DataGridCollection}" AutoGenerateColumns="False" > 
        <DataGrid.Columns> 
         <DataGridTextColumn Header="SuppNb" Binding="{Binding suppInvNumber}" Width="*"/> 
         <DataGridTextColumn Header="Shop" Binding="{Binding shop1.shop1}" Width="*"/> 
         <DataGridTextColumn Header="Date" Binding="{Binding date}" Width="*"/> 
         <DataGridTextColumn Header="Supplier" Binding="{Binding foodSupplier.supplier}" Width="*"/> 
         <DataGridTextColumn Header="Ref Supplier" Binding="{Binding refSupp}" Width="*"/> 
         <DataGridTextColumn Header="Unit" Binding="{Binding unit}" Width="*"/> 
         <DataGridTextColumn Header="Quantity" Binding="{Binding quantity}" Width="*"/> 
         <DataGridTextColumn Header="Prix/MOQ" Binding="{Binding unitPrice}" Width="*"/> 
         <DataGridTextColumn Header="Total Price" Binding="{Binding totalPrice}" Width="*"/> 
        </DataGrid.Columns> 
       </DataGrid> 
      </StackPanel> 

ответ

2

Неправильно связываться в SelectedItem. Вместо этого используйте SelectedValue с SelectedValuePath.

SelectedItem может быть привязан только к объекту (объекту). В то время как SelectedValue может быть привязан к значению, указанному в элементе SelectedValuePath.

Просто измените его, как показано ниже, и вы сможете получить результат из выпадающего списка.

  <ComboBox Name="supplierComboBox" 
         Margin="5" 
         ItemsSource="{Binding FoodSupplier}" 
         DisplayMemberPath="supplier" 
         SelectedValue="{Binding Supplier, Mode=OneWayToSource}" 
         SelectedValuePath="idfoodSupplier" 
         Width="71"/> 
+0

Я глуп. да, все хорошо. Спасибо. – Cantinou

+0

Не говорите этого. Мы все были там. Быть застрявшим в днях просто надсмотром. лол – cscmh99

0

Вы должны либо связать Comoboxes с некоторой команды в вашем ViewModel, так что ваш ViewModel знает, что вы выбрали?

Или вам необходимо передать выбранные элементы ComboBoxes в качестве параметров в команду поиска, чтобы в вашем методе поиска вы могли получить доступ к выбранным пользователем значениям.

Прямо сейчас вы обращаетесь непосредственно к Магазину, что бессмысленно. Вы предполагаете, что при выборе элемента в ShopComboBox переменная Shop в ViewModel получит это значение. Это не верно.

Когда вы связываете say ObservableCollection с DataGrid, и вы выбираете строку в DataGrid, ObservableCollection ничего не знает об этом выборе, но ваш DataGrid делает.

+0

Я хочу связать два комбокса с двумя свойствами. Когда я нажимаю кнопку, функция Search() выполняет фильтр. – Cantinou

Смежные вопросы