WPF MVVM无法绑定ComboBox

时间:2019-10-23 17:16:38

标签: wpf entity-framework mvvm

我正在使用MVVM,EntityFramework(数据库优先),并且我有2个与MSSQL的id_album相关的表。我不知道如何使用相册表绑定的ComboBox添加购买记录

edmx

What i want

XAML

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="63*"/>
        <ColumnDefinition Width="113*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="130*"/>
        <RowDefinition Height="57*"/>
    </Grid.RowDefinitions>
    <Border BorderThickness="1" BorderBrush="LightGray" CornerRadius="8" Margin="10.2,10,8,9.8" Background="White" Grid.RowSpan="2" Grid.Column ="1">
        <StackPanel Margin="0.2,9.2,0,9">
            <TextBlock Text="Sales" Style="{StaticResource textBlockStyle}"/>
            <DataGrid AutoGenerateColumns="False" ColumnWidth="*" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding Purchase.View}" CanUserReorderColumns="False" EnableRowVirtualization="false" EnableColumnVirtualization="false"  CanUserAddRows="False" Background="#FFA5A5A5" Height="208" Margin="10,20,10.2,0" VerticalAlignment="Top" BorderBrush="#FFA5A5A5">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Album" Width="*" Binding="{Binding Album.album_name}"/>
                    <DataGridTextColumn Header="Seller" Width="*" Binding="{Binding Employee.employee_name}"/>
                    <DataGridTextColumn Header="Number of copies" Width="160" Binding="{Binding purchase_amount}"/>
                    <DataGridTextColumn Header="Date" Width="*" Binding="{Binding purchase_date, StringFormat=\{0:dd/MM/yyyy HH:mm:ss\}}" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
            <Grid Height="251" Margin="0,10,0.2,0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
            </Grid>
            <Grid Height="58" Margin="10,15,364.2,0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Button Grid.Column="0" Style="{StaticResource AddStyle}" Content="Refresh" Command="{Binding RefreshEvent}" Width="Auto" Margin="25,8,24.6,8.2" Height="Auto"/>                  
            </Grid>
        </StackPanel>
    </Border>
    <Border BorderThickness="1" BorderBrush="LightGray" CornerRadius="8" Margin="8,10,5.8,10" Background="White" Grid.Column="0">
        <StackPanel x:Name="addStackPanel">
            <Grid Height="525">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Row="0" Text="Album" Style="{StaticResource textBlockStyle}"/>

                <ComboBox Grid.Column="1" Style="{StaticResource comboBoxStyle}" ItemsSource="{Binding Album.View}" SelectedItem="{Binding SelectedItem.id_album, Mode=TwoWay}" SelectedValuePath="id_album" DisplayMemberPath="album_name" IsSynchronizedWithCurrentItem="True"/>

                <TextBlock Grid.Row="1" Text="Seller" Style="{StaticResource textBlockStyle}"/>
                <TextBox Grid.Column="1" Grid.Row="1" Style="{StaticResource textBoxStyle}" Text="{Binding SelectedItem.id_employee, Mode=TwoWay}"/>
                <TextBlock Grid.Row="2" Text="Number of copies" Style="{StaticResource textBlockStyle}" Margin="10,34.8,10.4,34.4" Width="194"/>
                <TextBox Grid.Column="1" Grid.Row="2" Style="{StaticResource textBoxStyle}" Text="{Binding SelectedItem.purchase_amount,Mode=TwoWay}"/>
                <Button Grid.Row="5" Style="{StaticResource EditStyle}" Content="{Binding ButtonAddContent}" Command="{Binding AddEvent}" Width="Auto" Margin="25,17.4,24.4,26.8" Height="Auto"/>
                <Button Grid.Column="1" Grid.Row="5" Style="{StaticResource DeleteStyle}" Content="Save" Command="{Binding SaveEvent}" Width="Auto" Margin="25.4,0,25.2,26.8" Height="42.534" VerticalAlignment="Bottom"/>
            </Grid>
        </StackPanel>
    </Border>
</Grid>

这是我的ViewModel,它是从BaseViewModel继承的

PurchaseViewModel

    public class PurchaseViewModel : BaseViewModel, IPageViewModel {
    public CollectionViewSource Purchase { get; private set; }
    public CollectionViewSource Album { get; private set; }
    public CollectionViewSource Employee { get; private set; }
    public string Name {
        get => "Sales";
    }
    private Purchase selectedItem;
    public Purchase SelectedItem {
        get => selectedItem;
        set {
            selectedItem = value;
            OnPropertyChanged("SelectedItem");
            ButtonAddContent = "Add";
        }
    }

    public PurchaseViewModel() {
        Purchase = new CollectionViewSource();
        Album = new CollectionViewSource();
        Employee = new CollectionViewSource();
        RefreshData();
        SelectedItem = Purchase.View.CurrentItem as Purchase;
        SaveEvent = new SaveCommand(this);
        AddEvent = new AddCommand(this);
        RefreshEvent = new RefreshCommand(this);
    }
    public void RefreshData() {
        using (var dbContext = new MusicStoreDBEntities()) {
            Purchase.Source = dbContext.Purchases
                .Include(a => a.Album)
                .Include(emp => emp.Employee)
                .ToList();
            var employeeQuery = (from emp in dbContext.Employees
                         select new {
                             emp.id_employee,
                             emp.employee_name
                         }).ToList();
            Employee.Source = employeeQuery;
            Album.Source = (from a in dbContext.Albums
                            select new {
                                a.album_name,
                                a.id_album
                            }).ToList();
        }
    }
    public void SaveChanges() {
        try {
            using (var dbContext = new MusicStoreDBEntities()) {
                if (ButtonAddContent == "Cancel") {
                    AddPurchaseData(dbContext);
                    ButtonAddContent = "Add";
                } else {
                    EditPurchaseData(dbContext);
                }
            }
            RefreshData();
        } catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }
    public void AddPurchaseData(MusicStoreDBEntities dbContext) {
        dbContext.Purchases.Add(SelectedItem);
        dbContext.SaveChanges();
    }
    public void EditPurchaseData(MusicStoreDBEntities dbContext) {
        dbContext.Entry(SelectedItem).State = EntityState.Modified;
        dbContext.SaveChanges();
    }

BaseViewModel实现INotifyPropertyChanged

BaseViewModel

    public abstract class BaseViewModel : INotifyPropertyChanged {
    public SaveCommand SaveEvent { get; set; }
    public AddCommand AddEvent { get; set; }
    public ExportCommand ExportEvent { get; set; }
    public RefreshCommand RefreshEvent { get; set; }
    public DeleteCommand DeleteEvent { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string property) {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
    public BaseViewModel() {
        ButtonAddContent = "Add";
    }
    private string buttonAddContent;
    public string ButtonAddContent {
        get => buttonAddContent;
        set {
            buttonAddContent = value;
            OnPropertyChanged("ButtonAddContent");
        }
    }
}

AddCommand

public class AddCommand : ICommand {    
    private readonly dynamic baseViewModel;

    public AddCommand(BaseViewModel baseViewModel) {
        this.baseViewModel = baseViewModel;
    }

    public event EventHandler CanExecuteChanged {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter) {
        return true;
    }

    public void Execute(object parameter) {
        if (baseViewModel.ButtonAddContent == "Add") {
            switch (baseViewModel.Name) {
                case "Sales":
                    var purchase = new Purchase {
                        purchase_date = DateTime.Now
                    };
                    baseViewModel.SelectedItem = purchase;
                    break;                
            }
            baseViewModel.ButtonAddContent = "Cancel";
        } else {
            switch (baseViewModel.Name) {
                case "Sales":
                    baseViewModel.SelectedItem = baseViewModel.Purchase.View.CurrentItem as Purchase;
                    break;
            }
        }
    }
}

0 个答案:

没有答案