将ItemsControl按钮绑定到命令 - 命令不触发

时间:2014-12-14 06:42:43

标签: c# wpf mvvm binding itemscontrol

我遇到来自ItemsControl的按钮的命令绑定问题。由于某种原因,命令没有被触发。我的按钮通过绑定到ItemsControl的可观察集合显示。

我在SO中遵循了一些说明,例如绑定到relativesource和元素名称,但仍无法正常工作。

型号:

namespace InteractiveExam.Model
{
    class Resource
    {
        long _resourceID;

        public long ResourceID
        {
            get { return _resourceID; }
            set { _resourceID = value; }
        }


        string _resourceTitle;

        public string ResourceTitle
        {
            get { return _resourceTitle; }
            set { _resourceTitle = value; }
        }


        string _filename;

        public string Filename
        {
            get { return _filename; }
            set { _filename = value; }
        }


        string _resourceModuleID;

        public string ResourceModuleID
        {
            get { return _resourceModuleID; }
            set { _resourceModuleID = value; }
        }


        string _resourceType;

        public string ResourceType
        {
            get { return _resourceType; }
            set { _resourceType = value; }
        }


    }
}

ViewModel 1:

class ResourceViewModel : INotifyPropertyChanged
{
    Resource resource;

    public Resource Resource
    {
        get
        {
            return resource;
        }
        set
        {
            resource = value;
        }
    }

    public long ResourceID
    {
        get
        {
            return Resource.ResourceID;
        }
        set
        {
            if (Resource.ResourceID != value)
            {
                Resource.ResourceID = value;
                RaisePropertyChanged("ResourceID");
            }
        }
    }

    public string ResourceTitle
    {
        get
        {
            return Resource.ResourceTitle;
        }
        set
        {
            if (Resource.ResourceTitle != value)
            {
                Resource.ResourceTitle = value;
                RaisePropertyChanged("ResourceTitle");
            }
        }
    }

    public string Filename
    {
        get
        {
            return Resource.Filename;
        }
        set
        {
            if (Resource.Filename != value)
            {
                Resource.Filename = value;
                RaisePropertyChanged("Filename");
            }
        }
    }

    public string ResourceModuleID
    {
        get
        {
            return Resource.ResourceModuleID;
        }
        set
        {
            if (Resource.ResourceModuleID != value)
            {
                Resource.ResourceModuleID = value;
                RaisePropertyChanged("ResourceModuleID");
            }
        }
    }

    public string ResourceType
    {
        get
        {
            return Resource.ResourceType;
        }
        set
        {
            if (Resource.ResourceType != value)
            {
                Resource.ResourceType = value;
                RaisePropertyChanged("ResourceType");
            }
        }
    }

    #region PropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion

ViewModel 2(这是我的视图Datacontext):

class MultiMediaViewerViewModel : INotifyPropertyChanged
{
    string connectionStringLocal = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;

    public MultiMediaViewerViewModel()
    {
        LoadModules();
        LoadResources();
    }

    #region Module

    private Module module = new Module();
    static ObservableCollection<ModuleViewModel> _modules = new ObservableCollection<ModuleViewModel>();

    public static ObservableCollection<ModuleViewModel> Modules
    {
        get
        {
            return _modules;
        }
        set
        {
            _modules = value;
        }
    }

    private void LoadModules()
    {
        SqlConnection thisConnection = new SqlConnection(connectionStringLocal);
        thisConnection.Open();

        string Get_Data = "SELECT * FROM module ORDER BY moduleName";

        SqlCommand cmd = thisConnection.CreateCommand();
        cmd.CommandText = Get_Data;

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable("module");
        sda.Fill(dt);

        foreach (DataRow row in dt.Rows)
        {
            module.ModuleID = row["moduleID"].ToString();
            module.ModuleName = row["moduleName"].ToString();
            module.ModulePrerequisiteID = row["prerequisiteID"].ToString();
            module.ModuleCourseID = row["courseID"].ToString();

            _modules.Add(new ModuleViewModel {Module = new Module{ ModuleID = module.ModuleID, ModuleName = module.ModuleName, ModulePrerequisiteID = module.ModulePrerequisiteID, ModuleCourseID = module.ModuleCourseID } });
        }

        //close and dispose
        thisConnection.Close();
        thisConnection.Dispose();

        cmd.Dispose();
        dt.Dispose();
    }

    #endregion

    #region Resources

    private Resource resource = new Resource();
    static ObservableCollection<ResourceViewModel> _resources = new ObservableCollection<ResourceViewModel>();

    public static ObservableCollection<ResourceViewModel> Resources
    {
        get
        {
            return _resources;
        }
        set
        {
            _resources = value;
        }
    }

    private void LoadResources()
    {
        SqlConnection thisConnection = new SqlConnection(connectionStringLocal);
        thisConnection.Open();

        string Get_Data = "SELECT * FROM resource ORDER BY resourceTitle";

        SqlCommand cmd = thisConnection.CreateCommand();
        cmd.CommandText = Get_Data;

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable("resource");
        sda.Fill(dt);

        foreach (DataRow row in dt.Rows)
        {
            resource.ResourceID = Convert.ToInt64(row["id"]);
            resource.ResourceTitle = row["resourceTitle"].ToString();
            resource.Filename = row["filename"].ToString();
            resource.ResourceModuleID = row["resourceModuleID"].ToString();
            resource.ResourceType = row["resourceType"].ToString();

            _resources.Add(new ResourceViewModel { Resource = new Resource { ResourceID = resource.ResourceID, ResourceTitle = resource.ResourceTitle, Filename = resource.Filename, ResourceModuleID = resource.ResourceModuleID, ResourceType = resource.ResourceType } });
        }

        //close and dispose
        thisConnection.Close();
        thisConnection.Dispose();

        cmd.Dispose();
        dt.Dispose();
    }

    #endregion

    #region MediaPlayer

    string resourceFolder = ConfigurationManager.AppSettings["resourceFolder"].ToString();

    private MediaPlayer mediaPlayer = new MediaPlayer();

    static ObservableCollection<MediaPlayerViewModel> _mediaPlayers = new ObservableCollection<MediaPlayerViewModel>();

    public static ObservableCollection<MediaPlayerViewModel> MediaPlayers
    {
        get
        {
            return _mediaPlayers;
        }
        set
        {
            _mediaPlayers = value;
        }
    }

    private void LoadMediaElementDefaults()
    {
        //mediaPlayer.TimelineSlider.Maximum = mediaPlayer.MediaElementPlayer.NaturalDuration.TimeSpan.TotalMilliseconds;
        string mediaFullpath = resourceFolder + "Dubai2021.mp4";
        mediaPlayer.MediaUri = new Uri(mediaFullpath, UriKind.Absolute);

        //_mediaPlayers.Add(new MediaPlayerViewModel { MediaPlayer = new MediaPlayer { MediaUri = mediaPlayer.MediaUri } });
    }

    Uri _mediaUri;

    public Uri MediaUri
    {
        get
        {
            return _mediaUri;
        }
        set
        {
            if (_mediaUri != value)
            {
                _mediaUri = value;
                RaisePropertyChanged("MediaUri");
            }
        }
    }

    public ICommand PlayCommand { get { return new RelayCommand(PlayCommandExecute, CanPlayCommandExecute); } }

    void PlayCommandExecute()
    {
        string mediaFullpath = resourceFolder + "Dubai2021.mp4";
        MediaUri = new Uri(mediaFullpath, UriKind.Absolute);

        if (this.PlayRequested != null)
        {
            this.PlayRequested(this, EventArgs.Empty);
        }
    }

    bool CanPlayCommandExecute()
    {
        return true;
    }

    public event EventHandler PlayRequested;

}

查看:

&#13;
&#13;
<StackPanel DockPanel.Dock="Right" HorizontalAlignment="Right" 
            Width="250" VerticalAlignment="Stretch">
    <ScrollViewer HorizontalScrollBarVisibility="Disabled" 
                  VerticalScrollBarVisibility="Hidden" CanContentScroll="True" 
                  PanningMode="VerticalOnly" 
                  Height="{Binding ElementName=mainGrid,Path=ActualHeight}" 
                  ManipulationBoundaryFeedback="ScrollViewer_ManipulationBoundaryFeedback" 
                  Padding="0,0,0,130">
       <DockPanel>
         <StackPanel>
           <ItemsControl ItemsSource="{Binding Resources}">
             <ItemsControl.ItemTemplate>
                <DataTemplate>
                   <Button Template="{StaticResource ctButton}" Margin="0,0,0,5"
                           Tag="{Binding ResourceID}" 
                           Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType=Window},Path=DataContext.PlayCommand}">
                       <TextBlock 
                           Text="{Binding ResourceTitle}"
                           TextWrapping="Wrap"
                            Width="170"
                            Height="70" 
                            FlowDirection="LeftToRight"/>
                       </Button>
                     </DataTemplate>
                   </ItemsControl.ItemTemplate>
               </ItemsControl>
             </StackPanel>
         </DockPanel>
      </ScrollViewer>
  </StackPanel>
&#13;
&#13;
&#13;

0 个答案:

没有答案