2017-07-13 15 views
-1

私はMainWindowを持っています。ボタンを押すと、ViewModelのメソッドが呼び出されます。いくつかのXAMLで書かれたユーザーコントロールである私の見解から新しいVideocontrolをinstantiatsViewModelからメインウィンドウにusercontrolを戻す方法WPF

public void BtnOpenClick() 
{ 
    //DoStuff 
    VideoControl mediaplayer = new VideoControl 
} 

usercontrol私はViewModelからMainWindowに戻ってMVVMに戻ることができますか?

編集

私はMVVMパターンオフ誤解を持っていたし、私ははっきりとやろうとしたことは、パターンに違反します。

は、今の私は、私のモデルは、単にファイルIのウリである

<StackPanel> 
    <Local:VideoControl IconInfos="{Binding SourceVideos}"/> 
</StackPanel> 

私のViewModelはこの

class VideoControlViewModel : ViewModel 
{ 
    private ObservableCollection<Video> _Videos; 

    public ObservableCollection<Video> Videos 
    { 
     get { return _Videos; } 
     set { SetProperty(ref _Videos, value); } 
    } 
} 

のように見えます私は私のユーザーコントロールにバインドするメインウィンドウ内の溶液(VideoControlは)を持っています私のMediaElementで再生したい

public class Video 
{ 
    public Uri FileName { get; set; } 
} 

より多くのユーザーコントロール私はデータテンプレートを持っています私は今、私はボタンを呼ぶとき、私はObeservableコレクションに別の項目を追加することができますし、メディアプレーヤがアップにポップアップ表示されますについては、このコード

VideoControlViewModel _vm; 

public VideoControl() 
{ 
    InitializeComponent(); 
    _vm = (VideoControlViewModel) VideoGrid.DataContext; 
} 

public ObservableCollection<Video> IconInfos 
{ 
    get { return (ObservableCollection<Video>)GetValue(IconInfosProperty); } 
    set { SetValue(IconInfosProperty, value); } 
} 

public static readonly DependencyProperty IconInfosProperty = 
    DependencyProperty.Register("IconInfos", typeof(ObservableCollection<Video>), 
     typeof(VideoControl), new PropertyMetadata(null, OnIconInfosSet)); 

private static void OnIconInfosSet(DependencyObject d, 
    DependencyPropertyChangedEventArgs e) 
{ 
    ((VideoControl)d)._vm.Videos = e.NewValue as ObservableCollection<Video>; 
} 

を持っているの背後にあるし、いくつかのより多くのXAML

<UserControl.Resources> 
    <DataTemplate x:Key="VideoTemplate"> 
     <MediaElement x:Name="MediaPlayer" Source="{Binding FileName }"/> 
    </DataTemplate> 
</UserControl.Resources> 

<StackPanel Orientation="Horizontal"> 
       <ItemsControl ItemsSource="{Binding Videos}" 
          ItemTemplate="{StaticResource VideoTemplate}" 
          Grid.Row="1"> 
        <ItemsControl.ItemsPanel> 
         <ItemsPanelTemplate> 
          <WrapPanel /> 
         </ItemsPanelTemplate> 
        </ItemsControl.ItemsPanel> 
       </ItemsControl> 
      </StackPanel> 

とコードで選択されたウリのメインウィンドウ。

+2

これは、[XY問題]のように思えます(https://meta.stackexchange.com/questions/66377/what-is-the-xy-問題)。あなたは本当に何をしたいですか? –

+1

"ViewModelからMainWindowに戻ってユーザーコントロールを返す"ことについてMVVMはありません。ビューモデルはコントロールを作成しません。 – mm8

+0

@ mm8これについては本当にわかりません。私の答えはどのようにしてMVVMに違反しますか? –

答えて

0

コンテンツにあなたの制御を渡すようにしてください:

public void BtnOpenClick() 
    { 
     //DoStuff 
     VideoControl mediaplayer = new VideoControl(); 

     MainWindow.YourControl.Content = mediaplayer; 
    } 
関連する問題