2017-06-09 1 views
0

私は、DockPanelsで区切られた3つのセクションを持つWPF XAMLページを持っています。 1つのパネルには、コレクションにバインドされるINFRAGITICS XamDataGridコントロールが含まれています。純粋なMVVMの概念と依存性注入を使用して、WPFページ上の異なるコレクションで異なるパネルで使用可能なXamDataGridをバインドする方法。

  1. 純粋なMVVMの方法でDataContext/DataSourceプロパティを使用してXamDataGridコントロールをバインドしたいと思います。
  2. また、バインディングが依存関係注入によって行われるかどうかを理解することができれば嬉しいです。

私はさまざまなアプローチを試みましたが、成功しませんでした。私は参照のために私のコードを貼り付けました。親切に助けてください。

XAMLページ:

<Window x:Class="UserInterface.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:UserInterface" 
     xmlns:igDP="clr-namespace:Infragistics.Windows.DataPresenter;assembly=InfragisticsWPF.DataPresenter" 
      xmlns:igEditors="clr-namespace:Infragistics.Windows.Editors;assembly=InfragisticsWPF.Editors" 
      xmlns:sys="clr-namespace:System;assembly=mscorlib" 
     xmlns:dc ="clr-namespace:UserInterface.ViewModel" 
     xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" 
     mc:Ignorable="d" 
     Title="MainWindow"> 
    <Window.Resources> 
     <dc:GraphicViewModel x:Key="dataContext"/> 
    </Window.Resources> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height=".5*"/> 
      <RowDefinition Height=".5*"/> 
     </Grid.RowDefinitions> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width=".5*"/> 
      <ColumnDefinition Width=".5*"/> 
     </Grid.ColumnDefinitions> 

     <DockPanel Grid.Column="0" Grid.Row="0"> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="Auto"/> 
        <ColumnDefinition Width="Auto"/> 
        <ColumnDefinition Width="Auto"/> 
       </Grid.ColumnDefinitions> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="Auto"/> 
       </Grid.RowDefinitions> 
      </Grid> 
      <!--<StackPanel Orientation="Vertical" DockPanel.Dock="Top"> 
       <StackPanel Orientation="Horizontal" Margin="5" Grid.Row="0"> 
        <DockPanel> 
         <TextBlock Text="*.cfg File" Grid.Column="0" DockPanel.Dock="Left"/> 
         <Button Content="Browse..." Grid.Column="2" DockPanel.Dock="Right"/> 
         <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.cfg file..." Grid.Column="1" DockPanel.Dock="Right"/> 
        </DockPanel> 
       </StackPanel> 
       <StackPanel Orientation="Horizontal" Margin="5" Grid.Row="1"> 
        <TextBlock Text="*.ps File " Grid.Column="0"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.ps file..." Grid.Column="1"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
       </StackPanel> 
       <StackPanel Orientation="Horizontal" Margin="5" Grid.Row="2"> 
        <TextBlock Text="*.pic File " Grid.Column="0"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.pic file..." Grid.Column="1"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
       </StackPanel> 
       <StackPanel Orientation="Horizontal" Margin="5" Grid.Row="3"> 
        <TextBlock Text="*.xlsx File" Grid.Column="0"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.xlsx file..." Grid.Column="1"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
       </StackPanel> 
       <StackPanel Orientation="Horizontal" Margin="5" Grid.Row="4"> 
        <TextBlock Text="*.xlsx File"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.xlsx file..." Grid.Column="1"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
       </StackPanel> 
      </StackPanel>--> 
      <StackPanel Orientation="Horizontal"> 
       <StackPanel Orientation="Vertical" Margin="5" Grid.Row="0"> 
        <TextBlock MinHeight="20.5" Text="*.cfg File" Grid.Column="0"/> 
        <TextBlock MinHeight="20.5" Text="*.ps File " Grid.Column="0"/> 
        <TextBlock MinHeight="20.5" Text="*.pic File " Grid.Column="0"/> 
        <TextBlock MinHeight="20.5" Text="*.xlsx File" Grid.Column="0"/> 
        <TextBlock MinHeight="20.5" Text="*.xlsx File" Grid.Column="0"/>     
       </StackPanel> 
       <StackPanel Orientation="Vertical" Margin="5" Grid.Row="1"> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.cfg file..." Grid.Column="1" MinHeight="20.5"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.ps file..." Grid.Column="1" MinHeight="20.5"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse *.pic file..." Grid.Column="1" MinHeight="20.5"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse Model mapping file..." Grid.Column="1" MinHeight="20.5"/> 
        <TextBox FontStyle="Italic" FontWeight="Light" Text="Browse Parameter mapping file..." Grid.Column="1" MinHeight="20.5"/>     
       </StackPanel> 
       <StackPanel Orientation="Vertical" Margin="5" Grid.Row="2"> 
        <Button Content="Browse..." Grid.Column="2"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
        <Button Content="Browse..." Grid.Column="2"/> 
       </StackPanel>    
      </StackPanel> 
     </DockPanel> 
     <DockPanel Grid.Column="1" Grid.Row="0"> 
      <igDP:XamDataGrid x:Name="ItemsSource" DataContext="{Binding Source={StaticResource dataContext}, Path=ItemsSource, Mode=TwoWay}" Grid.Row="0" Margin="10" AutoFit="true"> 
       <igDP:XamDataGrid.ViewSettings> 
        <igDP:GridViewSettings/> 
       </igDP:XamDataGrid.ViewSettings> 

       <igDP:XamDataGrid.FieldSettings> 
        <igDP:FieldSettings LabelTextAlignment="Left" AllowRecordFiltering="true" FilterOperandUIType="ExcelStyle" FilterStringComparisonType="CaseInsensitive" FilterOperatorDefaultValue="Contains" 
             LabelClickAction="SortByOneFieldOnlyTriState" SortComparisonType="Default"/> 
       </igDP:XamDataGrid.FieldSettings> 
       <igDP:XamDataGrid.FieldLayoutSettings> 
        <igDP:FieldLayoutSettings DataErrorDisplayMode="ErrorIconAndHighlight" SupportDataErrorInfo="RecordsAndCells" SelectionTypeRecord ="Single"         
           AutoGenerateFields="False" FilterUIType="FilterRecord"/> 
       </igDP:XamDataGrid.FieldLayoutSettings> 
       <igDP:XamDataGrid.FieldLayouts> 
        <igDP:FieldLayout> 
         <igDP:FieldLayout.Fields> 
          <igDP:Field Name="IsSelected" Label="Select" HorizontalContentAlignment="Left" Width="Auto" VerticalContentAlignment="Center"> 
           <igDP:Field.Settings> 
            <igDP:FieldSettings DataItemUpdateTrigger="OnCellValueChange"> 
             <igDP:FieldSettings.LabelPresenterStyle> 
              <Style TargetType="{x:Type igDP:LabelPresenter}"> 
               <Setter Property="ContentTemplate"> 
                <Setter.Value> 
                 <DataTemplate> 
                  <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" Content="" /> 
                 </DataTemplate> 
                </Setter.Value> 
               </Setter> 
              </Style> 
             </igDP:FieldSettings.LabelPresenterStyle> 
            </igDP:FieldSettings> 
           </igDP:Field.Settings> 
          </igDP:Field> 
          <igDP:Field Label="Name" Name="Name" AllowEdit="False" HorizontalContentAlignment="Left" Width="Auto">        
          </igDP:Field> 
          <igDP:Field Label="Type" Name="Type" AllowEdit="False" HorizontalContentAlignment="Left" Width="*"/> 
          <igDP:Field Label="Background" Name="Background" AllowEdit="False" HorizontalContentAlignment="Left" Width="Auto"/> 
          <igDP:Field Label="Width" Name="Width" AllowEdit="False" HorizontalContentAlignment="Right" Width="Auto"/> 
          <igDP:Field Label="Height" Name="Height" AllowEdit="False" HorizontalContentAlignment="Right" Width="Auto"/>        
         </igDP:FieldLayout.Fields> 
        </igDP:FieldLayout> 
       </igDP:XamDataGrid.FieldLayouts> 
      </igDP:XamDataGrid> 
     </DockPanel> 
     <DockPanel Grid.Column="0" Grid.Row="1" Grid.RowSpan="2"> 
      <StackPanel Orientation="Vertical" DockPanel.Dock="Bottom">  
       <TextBox Text="Sample Text1"/> 
       <TextBox Text="Sample Text2"/>  
       <TextBox Text="Sample Text3"/> 
       <TextBox Text="Sample Text4"/>  
      </StackPanel> 
     </DockPanel> 
     <!--</StackPanel>--> 
    </Grid> 
</Window> 
背後

XAMLページのコード:

namespace UserInterface 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent();     
      //GraphicViewModel obj = new GraphicViewModel();     
      //ItemsSource.DataSource = obj.ItemsSource; 
     } 

     #region INotifyPropertyChanged Members 

     public event PropertyChangedEventHandler PropertyChanged; 

     private void NotifyPropertyChanged(string info) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(info)); 
      } 
     } 

     #endregion INotifyPropertyChanged Members 
     public GraphicViewModel GraphicViewModel 
     { 
      get { return this.DataContext as GraphicViewModel; } 
      set 
      { 
       this.DataContext = value; 
       if (this.DataContext != null) 
        NotifyPropertyChanged("GraphicViewModel"); 
      } 
     } 

     private void CheckBox_Checked(object sender, RoutedEventArgs e) 
     { 

     } 

     private void CheckBox_Unchecked(object sender, RoutedEventArgs e) 
     { 

     } 
    } 
} 

モデルクラス:

namespace UserInterface.Model 
{ 
    public class GraphicsModel : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     protected virtual void NotifyOfPropertyChange(string property) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 

     private bool _isSelected; 
     public bool IsSelected 
     { 
      get { return _isSelected; } 
      set 
      { 
       if (_isSelected == value) return; 

       _isSelected = value; 
       NotifyOfPropertyChange("IsSelected"); 
      } 
     } 

     private string _name = string.Empty; 
     public string Name 
     { 
      get { return _name; } 
      set 
      { 
       if (_name != value) 
        _name = value; 
       NotifyOfPropertyChange("Name"); 
      } 
     } 

     private string _type = string.Empty; 
     public string Type 
     { 
      get { return _type; } 
      set 
      { 
       if (_type != value) 
        _type = value; 
       NotifyOfPropertyChange("Type"); 
      } 
     } 

     private string _width = string.Empty; 
     public string Width 
     { 
      get { return _width; } 
      set 
      { 
       if (_width != value) 
        _width = value; 
       NotifyOfPropertyChange("Width"); 
      } 
     } 

     private string _height = string.Empty; 
     public string Height 
     { 
      get { return _height; } 
      set 
      { 
       if (_height != value) 
        _height = value; 
       NotifyOfPropertyChange("Height"); 
      } 
     } 
    } 
} 

のViewModelクラス:

namespace UserInterface.ViewModel 
{ 
    public class GraphicViewModel : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     protected virtual void NotifyOfPropertyChange(string property) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 

     private ObservableCollection<GraphicsModel> _itemsSource = new ObservableCollection<GraphicsModel>(); 


     // MainWindow _view = null; 
     public ObservableCollection<GraphicsModel> ItemsSource 
     { 
      get { return _itemsSource; } 
      set 
      { 
       if (_itemsSource == value) return; 

       _itemsSource = value; 
       NotifyOfPropertyChange("ItemsSource"); 
      } 
     } 

     public GraphicViewModel() 
     { 
      //_view = view;   
      _itemsSource = new ObservableCollection<GraphicsModel>() { new GraphicsModel() { Name = "sdasdad", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } , 
      new GraphicsModel() { Name = "sdsa", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "sdasdad", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "asas", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,new GraphicsModel() { Name = "rewwe", Type = "Model", IsSelected = false, Height = "1000", Width = "1370" } ,};    
      //view.GraphicViewModel = this; 
     } 
    } 
} 
+1

観察:あなたの ''あなたはGraphicViewModel'プロパティを設定されていませんMainWindow'でDataContextを設定します。代わりに、ViewmodelをResourcesセクションに保存し、StaticResource経由でバインドします。これは完全に奇妙です。あなたがそれを使用したいwaouldどの方法を決定します。それは、コードによってwindow.DataContext' 'として設定されるべきか、あなたがしたい場合には、(両方ともOKとほとんど同じです)XAMLでのDataContextとして設定、またはしなければならないのいずれかリソース内に保持し、コードを適切に記述し、DataContextを参照しないでください(NULLのままになります) – quetzalcoatl

+0

と関連して(2)いいえ、そうではありません。 XAMLの通常の{Binding}マークアップは、DIと完全に無関係です。 '{Binding}'はSource(またはSourceが指定されていない場合はDataContext)のみを監視し、そのSource(DataContext)のPath(property.property.property.xxx)を監視します。これはそれと同じくらい簡単です。 DI容器との相互作用は全くありません。 – quetzalcoatl

+0

ありがとうございます。 XAMLのXamdatagridに直接DataContextを設定したいと思います。私はそれを試しましたが、成功しなかったので、ここに作業/変更されたコードを貼り付けてください。私が間違っていること。 – user3249586

答えて

0

あなたはあなたは、「タイプGraphicViewModelのプロパティと名前、それのDataContextを作成する」と言っている

<Window.Resources> 
    <dc:GraphicViewModel x:Key="dataContext"/> 
</Window.Resources> 

を書きます。それはほとんどのコードビハインドでこのような何かをやってとまったく同じです:

private GraphicViewModel dataContext = new GraphicViewModel(); 

あなたは

<igDP:XamDataGrid DataContext="{Binding Source={StaticResource dataContext}, Path=ItemsSource, Mode=TwoWay}" .. /> 

を書くときに、「dataContext.ItemsSourceigDP:XamDataGrid.DataContextプロパティをバインドする」と言っています。

グリッドが読み込まれない理由は、実際には.DataContextプロパティは何も行いません。これは、コントロールの背後にあるデータの保持者に過ぎません。あなたは

<igDP:XamDataGrid ItemsSource="{Binding MyProperty}" /> 

を書くことだったのであればそれは、WPFを伝える「XamDataGrid.DataContext.MyPropertyに等しいXamDataGrid.ItemsSourceプロパティを設定」することです。

上記のコードでは、DataContextをdataContext.ItemsSourceと等しく設定しているため、値はdataContext.ItemsSource.MyProperty(もちろん存在しません)に設定しようとします。あなたが実際に必要なもの

<igDP:XamDataGrid ItemsSource="{Binding Source={StaticResource dataContext}, Path=ItemsSource}" .. /> 

のようなものですこれは、「DataContextの」という名前の<Window.Resources>で作成された静的リソースに(それはからそのデータ行を構築するプロパティである)グリッドの.ItemsSourceプロパティをバインドし、そのオブジェクトのプロパティはItemsSourceとなります。

ここで2番目の問題は、あなたのコードに複数のViewModelのコピーがあるようです。個人的には、GraphicViewModelの場合のように、XAMLでオブジェクトを作成することは絶対にお勧めしません。代わりに、私はこのような何かをお勧めします:

public MainWindow() 
{ 
    InitializeComponent();     
    this.DataContext = new GraphicViewModel(); 
} 

は、今ではこれがGraphicViewModelの新しいインスタンスを作成しますが、どこでもそれを保存しないことに留意すべきです。 this.DataContextから GraphicViewModelにキャストせずに他のコードビハインドでこのオブジェクトにアクセスする場合は、値をどこかに格納する必要があります。

Window.DataContextが設定されたら、カスタムのSourceプロパティを指定せずにバインディングを書き込むことができます。

<igDP:XamDataGrid ItemsSource="{Binding ItemsSource}" .. /> 

WPFコントロールは、特に設定されていない場合、デフォルトで親からDataContextを検索するため、これが機能します。それはそれはあなたがあなたのGraphicViewModelの新しいインスタンスにコンストラクタで設定したWindow.DataContextに実行されるまでのDataContextで何かを探して、ビジュアルツリーを移動するので、したがって、この場合には、xamDataGridのための.DataContextプロパティはnullです。 DataContextプロパティを理解するために探している人々のために

、私は通常、同じ事のすべての時間を再入力することを避けるためにthis SO answerに送信します。私はあなたがまだDataContextが何であるか、それがどのように使われているのかを理解するために働いているなら、それを読むことをお勧めします。依存性の注入は別の何かで、全くここでは使用されないだろう、と述べた。また

+0

ありがとうございます。あなたの説明からわかったことは、それらの変更をしようとしましたが、まだグリッドは空です。言いたいことは、XamDataGridにItemsSourceプロパティがなく、DataSourceプロパティがないことです。私の更新されたコードは以下の通りです:public MainWindow() { InitializeComponent(); ItemsSource.DataContext = new GraphicViewModel(); }そして、 user3249586

+0

@ user3249586 [WPF Snoop]のようなツールをダウンロードすることをお勧めします(https: //snoopwpf.codeplex.com/)、実行時に正しいことを確認するためにDataContextを調べます。おそらくそれはそうでないように聞こえます – Rachel

+0

小さな訂正 - GraphicViewModel型のプロパティを作成してdataContextという名前をつける単語を開きます - それはそれとはまったく真実ではありません。あなたはおそらくコンポーネント 'x:Name'(あなたが書いたのと似たような方法でゆるやかに記述されています)を考えましたが、リソース' x:Key'のコンテキストで書いています(これは 'window.Resources [key ] 'リソース辞書)。リソースディクショナリは共有、スタイル、テーマなどのおかげでそれよりはるかに複雑ですが、ここでは実際には表示されないものはほとんどありません。 – quetzalcoatl

0

ありがとう@Rachel、@ダニエルフィリポフ& @quetzalcoatl、私は今働いています。下記のファイルに行われた変更:

MainWindow.xaml.cs

public MainWindow() 
     { 
      InitializeComponent();   
      ItemsSource.DataContext= new GraphicViewModel(); 
     } 

MainWindow.xaml:

<igDP:XamDataGrid x:Name="ItemsSource" DataSource="{Binding ItemsSource, Mode=TwoWay}" .../> 
関連する問題