Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从集合中删除组合框SelectedItem_C#_Wpf_Xaml_Mvvm_Data Binding - Fatal编程技术网

C# 从集合中删除组合框SelectedItem

C# 从集合中删除组合框SelectedItem,c#,wpf,xaml,mvvm,data-binding,C#,Wpf,Xaml,Mvvm,Data Binding,基本上我对所有这些都是全新的,我正在尝试在MVVM的环境中学习C。这将是一个简单的CRUD程序,现在我正忙于从相应的集合中删除一个组合框SelectedItem 相关视图模型代码: public class AlbumViewModel { private ObservableCollection<AlbumModel> albums; public AlbumViewModel() { this.albums = new Observabl

基本上我对所有这些都是全新的,我正在尝试在MVVM的环境中学习C。这将是一个简单的CRUD程序,现在我正忙于从相应的集合中删除一个组合框
SelectedItem

相关视图模型代码:

public class AlbumViewModel
{
    private ObservableCollection<AlbumModel> albums;

    public AlbumViewModel()
    {
        this.albums = new ObservableCollection<AlbumModel>();
        LoadAlbums();
    }

    public ObservableCollection<AlbumModel> Albums
    { 
        get { return this.albums; }
    }

    public void LoadAlbums()
    {
        albums.Add(new AlbumModel("No Love/Deep Web", "Death Grips"));
        albums.Add(new AlbumModel("In Defense of the Genre", "Say Anything"));
        albums.Add(new AlbumModel("Picaresque", "The Decemberists"));
        albums.Add(new AlbumModel("In Evening Air", "Future Islands"));
        albums.Add(new AlbumModel("You're Gonna Miss It All", "Modern Baseball"));
    }

    #region RelayCommand
    private RelayCommand _deleteCommand;

    public ICommand DeleteCommand
    {
        get
        {
            if (_deleteCommand == null)
            {
                _deleteCommand = new RelayCommand(param => DeleteItem());
            }

            return _deleteCommand;
        }
    }
    #endregion

    #region DeleteItem()
    private AlbumModel SelectedItem { get; set; }

    private void DeleteItem()
    {
        if (SelectedItem != null)
        {
            this.albums.Remove(SelectedItem);
            this.SelectedItem = null;
        }
    }
    #endregion


}
public class AlbumModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    // AlbumModel members, properties, constructor
}

#region RelayCommand
public class RelayCommand : ICommand
{
    // fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    // ctors
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {

    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    // ICommand members
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

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

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
我怀疑这是我的数据绑定错误,但我很难理解错误的含义。我希望大家能从任何角度看待问题

  • SelectedItem
    应该是公共的。绑定需要这样做
  • 您尝试绑定到方法(
    DeleteItem
    ),而不是命令(
    DeleteCommand
  • SelectedItem
    应该是公共的。绑定需要这样做
  • 您尝试绑定到方法(
    DeleteItem
    ),而不是命令(
    DeleteCommand

  • 重复的VM实例是什么,一个在资源中,一个作为DataContext?重复的VM实例是什么,一个在资源中,一个作为DataContext?谢谢!它们看起来很简单,所以忽略它们很尴尬,但正如我所说的,我对整个概念是全新的,学习它是一个过程。你能详细解释一下你在之前的评论中所说的“先看”是什么意思吗?复制虚拟机呢?这会很有帮助。您在
    Window.DataContext
    Window.Resources
    中都有VM实例。
    DataContext
    中应该只有一个,或者您可以在参考资料中创建一个,然后在以后的
    DataContext
    中引用它。“视图优先”的意思是,您在视图中创建视图模型的方式与之前相同(两次)。在我看来,WPF准备在所有情况下适当处理这是一种糟糕的方法。另一种选择是视图模型优先。有关详细信息,请搜索google或stack overflow。@korina:谢谢!它们看起来很简单,所以忽略它们很尴尬,但正如我所说的,我对整个概念是全新的,学习它是一个过程。你能详细解释一下你在之前的评论中所说的“先看”是什么意思吗?复制虚拟机呢?这会很有帮助。您在
    Window.DataContext
    Window.Resources
    中都有VM实例。
    DataContext
    中应该只有一个,或者您可以在参考资料中创建一个,然后在以后的
    DataContext
    中引用它。“视图优先”的意思是,您在视图中创建视图模型的方式与之前相同(两次)。在我看来,WPF准备在所有情况下适当处理这是一种糟糕的方法。另一种选择是视图模型优先。有关详细信息,请搜索google或堆栈溢出。@korina:
    <Window x:Class="AlbumsCRUD2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AlbumsCRUD2.ViewModels"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:AlbumViewModel />
    </Window.DataContext>
    <Window.Resources>
        <local:AlbumViewModel x:Key="albums" />
    </Window.Resources>
    <Grid>
    <GroupBox Grid.Row="1" Grid.Column="1" HorizontalContentAlignment="Center" Header="View Existing">
            <StackPanel>
                <Label Content="Album" />
    
                <ComboBox Name="albumComboBox" 
                          ItemsSource="{Binding Path=Albums}" 
                          DisplayMemberPath="AlbumName" 
                          SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    
                <Label Content="Artist" />
                <TextBox Text="{Binding ElementName=albumComboBox, Path=SelectedItem.ArtistName}" 
                         IsEnabled="False" />
    
                <Button Name="deleteBtn" Width="100" Margin="30"
                        Command="{Binding DeleteItem}"
                        Content="Delete" />
            </StackPanel>
        </GroupBox>
    </Grid>
    </Window>
    
    System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedItem' property not found on 'object' ''AlbumViewModel' (HashCode=12507741)'. BindingExpression:Path=SelectedItem; DataItem='AlbumViewModel' (HashCode=12507741); target element is 'ComboBox' (Name='albumComboBox'); target property is 'SelectedItem' (type 'Object')
    System.Windows.Data Error: 40 : BindingExpression path error: 'DeleteItem' property not found on 'object' ''AlbumViewModel' (HashCode=12507741)'. BindingExpression:Path=DeleteItem; DataItem='AlbumViewModel' (HashCode=12507741); target element is 'Button' (Name='deleteBtn'); target property is 'Command' (type 'ICommand')