0

Вопрос: Как отобразить данные в IndexesView?
IndexesView отображается в MainWindow
Как отобразить IndexesView в ManagerIndexesView?
Т.е. как и где правильно прописать биндинг к IndexesView?

https://github.com/jhon65496/DataDisplayWpfApp1

При отладке получаю сообщение в VS:

System.Windows.Data Error: 40 : BindingExpression path error: 'IndexesViewModel2' property not found on 'object' ''ManagerIndexesViewModel' (HashCode=22385437)'.

BindingExpression:Path=IndexesViewModel2; DataItem='ManagerIndexesViewModel' (HashCode=22385437); target element is 'ContentControl' (Name=''); target property is 'Content' (type 'Object')

Pic-1
введите сюда описание изображения

Pic-2
введите сюда описание изображения

App.xaml.cs

public partial class App : Application
{
    public App()
    {
    }
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // AppManager appManager = new AppManager();
    MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
    MainWindow mainWindow = new MainWindow();
    mainWindow.DataContext = mainWindowViewModel;
    mainWindow.Show();
}

}

App.xaml

<Application x:Class="DataDisplayWpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:DataDisplayWpfApp1">
    <Application.Resources>
&lt;/Application.Resources&gt;

</Application>

=== === === === === === === === === === === === === === === ===

IndexCalculation

public class IndexCalculation
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

MainMenuItemMainWindow

internal class MainMenuItemMainWindow
{
    public int Id { get; set; }
    public string Name { get; set; }             
    public string Alias { get; set; }
}

=== === === === === === === === === === === === === === === ===

DataContextApp

public class DataContextApp
{
    public DataContextApp()
    {
        GenerateDataСalculationIndex();
}


private ObservableCollection&lt;IndexCalculation&gt; calculationIndexes;
public ObservableCollection&lt;IndexCalculation&gt; СalculationIndexes
{
    get { return calculationIndexes; }
    set { calculationIndexes = value; }
}


public void GenerateDataСalculationIndex()
{
    var calculationIndexes = new ObservableCollection&lt;IndexCalculation&gt;();
    for (int i = 1; i &lt; 11; i++)
    {
        var indexCalculation = new IndexCalculation()
        {
            Id = i,
            Name = $&quot;NameIndex-{i}&quot;,
            Description = $&quot;DescriptionIndex-{i}&quot;
        };
        calculationIndexes.Add(indexCalculation);
    }

    СalculationIndexes = calculationIndexes;
}

}

=== === === === === === === === === === === === === === === ===

MainWindowViewModel

internal class MainWindowViewModel : BaseVM
{
public IndexesViewModel indexesViewModel;        
public ManagerIndexesViewModel managerIndexesViewModel;        
DataContextApp DataContextApp;

public MainWindowViewModel()
{
    // this.appManager = appManager;

    DataContextApp = new DataContextApp();

    managerIndexesViewModel = new ManagerIndexesViewModel(DataContextApp);
    indexesViewModel = new IndexesViewModel(DataContextApp);

    LoadItemMainMenu();
}


#region Title
private string title = &quot;App `DataDisplayWpfApp1`. Prop title&quot;;

public string Title 
{
    get { return title; }
    set { title = value; }
}
#endregion

#region mainMenuItems        
private ObservableCollection&lt;MainMenuItemMainWindow&gt; mainMenuItems;

public ObservableCollection&lt;MainMenuItemMainWindow&gt; MainMenuItems
{
    get { return mainMenuItems; }
    set
    {
        mainMenuItems = value;
        RaisePropertyChanged(nameof(MainMenuItemMainWindow));
    }
}
#endregion

#region SelectedItem
private MainMenuItemMainWindow selectedMainMenuItem;

public MainMenuItemMainWindow SelectedMainMenuItem
{
    get { return selectedMainMenuItem; }
    set 
    {                 
        selectedMainMenuItem = value;                

        SwitchView(selectedMainMenuItem.Alias);

        RaisePropertyChanged(nameof(CurrentView));
    }
}
#endregion


private BaseVM currentView;
public BaseVM CurrentView
{
    get { return currentView; }
    set
    {
        currentView = value;
        RaisePropertyChanged(nameof(CurrentView));
    }
}


private string titleDetail = &quot;TitleDetail&quot;;

public string TitleDetail
{
    get { return titleDetail; }
    set 
    { 
        titleDetail = value;
        Debug.WriteLine($&quot;titleDetail -- {titleDetail}&quot;);
        RaisePropertyChanged(nameof(TitleDetail));
    }
}



public void LoadItemMainMenu()
{
    mainMenuItems = new ObservableCollection&lt;MainMenuItemMainWindow&gt;()
    {
        new MainMenuItemMainWindow(){ Name = &quot;Управление коэффициентами&quot;, Alias =&quot;ManagerIndexes&quot; },
        new MainMenuItemMainWindow(){ Name = &quot;Коэффициенты&quot;, Alias =&quot;Indexes&quot;  },
        new MainMenuItemMainWindow(){ Name = &quot;Поставщки&quot;, Alias =&quot;Provider&quot;  }
    };
}

public void SwitchView(string nameView)
{
    switch (nameView)
    {
        case &quot;ManagerIndexes&quot;:                    
            CurrentView = managerIndexesViewModel;
            break;

        case &quot;Indexes&quot;:                    
            CurrentView = indexesViewModel;
            break;
    }
}

}

=== === === === === === === === === === === === === === === ===
ManagerIndexesViewModel

public class ManagerIndexesViewModel : BaseVM
{
    IndexesViewModel IndexesViewModel2 { get; }
public DataContextApp DataContextApp;


public ManagerIndexesViewModel(DataContextApp DataContextApp)
{
    this.DataContextApp = DataContextApp;

    IndexesViewModel2 = new IndexesViewModel(this);

}

private IndexCalculation selectedIndexCalculation;

public IndexCalculation SelectedIndexCalculation
{
    get { return selectedIndexCalculation; }
    set
    {
        selectedIndexCalculation = value;

        RaisePropertyChanged(nameof(SelectedIndexCalculation));          
    }
}

}

=== === === === === === === === === === === === === === === ===

IndexesViewModel

public class IndexesViewModel : BaseVM
{   
    ManagerIndexesViewModel managerIndexesViewModel;
DataContextApp DataContextApp;

public IndexesViewModel(ManagerIndexesViewModel managerIndexesViewModel)
{   

    this.managerIndexesViewModel = managerIndexesViewModel;
    this.DataContextApp = this.managerIndexesViewModel.DataContextApp;

    СalculationIndexs = DataContextApp.СalculationIndexes;            
}

public IndexesViewModel(DataContextApp DataContextApp)
{
    this.DataContextApp = DataContextApp;

    СalculationIndexs = DataContextApp.СalculationIndexes;
}




private ObservableCollection&lt;IndexCalculation&gt; calculationIndexs;

public ObservableCollection&lt;IndexCalculation&gt; СalculationIndexs
{
    get { return calculationIndexs; }
    set 
    { 
        calculationIndexs = value;
        RaisePropertyChanged(nameof(СalculationIndexs));
    }
}

private IndexCalculation selectedIndexCalculation;

public IndexCalculation SelectedIndexCalculation
{
    get { return selectedIndexCalculation; }
    set 
    { 
        selectedIndexCalculation = value;

        this.managerIndexesViewModel.SelectedIndexCalculation = selectedIndexCalculation;                

        RaisePropertyChanged(nameof(SelectedIndexCalculation));
    }
}


public void LoadDataTest2()
{
    СalculationIndexs = this.DataContextApp.СalculationIndexes;                       
}


}

=== === === === === === === === === === === === === === === ===
IndexesView

<UserControl x:Class="DataDisplayWpfApp1.Views.Views.IndexesView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vvm   =&quot;clr-namespace:DataDisplayWpfApp1.ViewModels.Views&quot;
         xmlns:local=&quot;clr-namespace:DataDisplayWpfApp1.Views.Views&quot;             
         mc:Ignorable=&quot;d&quot; 
         d:DesignHeight=&quot;450&quot; d:DesignWidth=&quot;800&quot;&gt;    
&lt;DockPanel&gt;
    &lt;UniformGrid DockPanel.Dock=&quot;Top&quot; Rows=&quot;1&quot; Margin=&quot;-3,3&quot;&gt;
        &lt;TextBlock FontSize =&quot;30&quot;&gt;IndexesView&lt;/TextBlock&gt;
        &lt;!--&lt;Button Content=&quot;Load&quot;
                        Command=&quot;{}&quot;
                        CommandParameter=&quot;{}&quot;    
                        Foreground=&quot;Blue&quot; Padding=&quot;0,5&quot; Margin=&quot;3,0&quot;/&gt;

        &lt;Button Content=&quot;Create&quot;
                        Command=&quot;&quot;
                        CommandParameter=&quot;&quot;
                        Foreground=&quot;Green&quot; Padding=&quot;0,5&quot; Margin=&quot;3,0&quot;/&gt;--&gt;
    &lt;/UniformGrid&gt;
    &lt;DataGrid Grid.Row=&quot;1&quot; 
                ItemsSource=&quot;{Binding СalculationIndexs}&quot;
                SelectedItem=&quot;&quot;                          
                SelectedIndex=&quot;2&quot;
                x:Name=&quot;MainDataGrid&quot;                                                             
                AutoGenerateColumns=&quot;False&quot;
                CanUserAddRows=&quot;True&quot;
                GridLinesVisibility=&quot;Vertical&quot;                                  
                VerticalGridLinesBrush=&quot;DarkGray&quot;
                 AlternatingRowBackground=&quot;LightGray&quot;
                 &gt;
        &lt;DataGrid.Columns&gt;
            &lt;DataGridTextColumn Header=&quot;id&quot; Binding=&quot;{Binding Id}&quot; Width=&quot;Auto&quot;/&gt;
            &lt;DataGridTextColumn Header=&quot;Имя&quot; Binding=&quot;{Binding Name}&quot;/&gt;
            &lt;DataGridTextColumn Header=&quot;Description&quot;  Binding=&quot;{Binding Description}&quot; Width=&quot;*&quot;/&gt;
        &lt;/DataGrid.Columns&gt;
    &lt;/DataGrid&gt;
&lt;/DockPanel&gt;

</UserControl>

=== === === === === === === === === === === === === === === ===
ManagerIndexesView

<UserControl x:Class="DataDisplayWpfApp1.Views.Views.ManagerIndexesView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"              
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:v ="clr-namespace:DataDisplayWpfApp1.Views.Views"             
             xmlns:vm="clr-namespace:DataDisplayWpfApp1.ViewModels"             
             xmlns:vvm="clr-namespace:DataDisplayWpfApp1.ViewModels.Views"             
             xmlns:local="clr-namespace:DataDisplayWpfApp1.Views.Views" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <!--<UserControl.Resources>        
        <DataTemplate DataType="{x:Type vvm:IndexesViewModel}">
            <v:IndexesView DataContext="{Binding}"/>
        </DataTemplate>        
    </UserControl.Resources>-->
    <Grid>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="350" MinWidth="200"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
        &lt;GroupBox Grid.Column=&quot;0&quot; Header=&quot;Управление индексами&quot;&gt;
            &lt;Grid&gt;
                &lt;Grid.RowDefinitions&gt;
                    &lt;RowDefinition /&gt;
                    &lt;RowDefinition Height=&quot;auto&quot;/&gt;
                    &lt;RowDefinition /&gt;
                &lt;/Grid.RowDefinitions&gt;

                &lt;GroupBox Grid.Row=&quot;0&quot; Header=&quot;Индексы&quot;&gt;                        
                    &lt;v:IndexesView DataContext=&quot;{Binding IndexesViewModel2}&quot;/&gt;
                    &lt;!--&lt;v:IndexesView /&gt;--&gt;
                    &lt;!--&lt;ContentControl Content=&quot;{Binding IndexesViewModel2}&quot;/&gt;--&gt;
                &lt;/GroupBox&gt;

                &lt;!--  GridSplitter --&gt;
                &lt;GridSplitter Grid.Row=&quot;1&quot; HorizontalAlignment=&quot;Stretch&quot; Height=&quot;3&quot;/&gt;
                &lt;!-- **  ========== **  --&gt;

                &lt;GroupBox Grid.Row=&quot;2&quot; Header=&quot;ИндексыПоставщкик&quot;&gt;
                    &lt;!--&lt;ContentControl Content=&quot;{Binding IndexesProvidersView}&quot;/&gt;--&gt;
                    &lt;!--&lt;v:ProvidersAssignedIndexCalculationView DataContext=&quot;{Binding ProvidersAssignedIndexViewModel}&quot;/&gt;--&gt;
                &lt;/GroupBox&gt;

            &lt;/Grid&gt;
        &lt;/GroupBox&gt;
        &lt;GroupBox Grid.Column=&quot;1&quot; Header=&quot;Поставщики&quot;&gt;
            &lt;!--&lt;ContentControl Content=&quot;{Binding ProvidersView}&quot;/&gt;--&gt;
            &lt;!--&lt;v:ProvidersNotAssignedIndexCalculationView DataContext=&quot;{Binding ProvidersNotAssignedIndexViewModel}&quot;/&gt;--&gt;
        &lt;/GroupBox&gt;
        &lt;GridSplitter Grid.Column=&quot;0&quot; HorizontalAlignment=&quot;Right&quot; Width=&quot;3&quot;/&gt;
    &lt;/Grid&gt;
&lt;/Grid&gt;

</UserControl>

=== === === === === === === === === === === === === === === ===

MainWindow

<Window x:Class="DataDisplayWpfApp1.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:DataDisplayWpfApp1"
        xmlns:vm    ="clr-namespace:DataDisplayWpfApp1.ViewModels"
        xmlns:vvm   ="clr-namespace:DataDisplayWpfApp1.ViewModels.Views"
        xmlns:v     ="clr-namespace:DataDisplayWpfApp1.Views.Views"
        d:DataContext="{d:DesignInstance Type=vm:MainWindowViewModel, IsDesignTimeCreatable=True}"
        mc:Ignorable="d"
        Title="{Binding Title}" 
        Height="800" Width="900">
    <Window.Resources>
        <DataTemplate DataType="{x:Type vvm:ManagerIndexesViewModel}">
            <v:ManagerIndexesView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vvm:IndexesViewModel}">
            <v:IndexesView />
        </DataTemplate>
&lt;/Window.Resources&gt;
&lt;Grid&gt;
    &lt;Grid.ColumnDefinitions&gt;
        &lt;ColumnDefinition Width=&quot;200&quot; MinWidth=&quot;200&quot;/&gt;
        &lt;ColumnDefinition Width=&quot;*&quot;/&gt;
    &lt;/Grid.ColumnDefinitions&gt;

    &lt;!--Группы--&gt;
    &lt;GroupBox Grid.Column=&quot;0&quot; Header=&quot;Меню&quot;&gt;
        &lt;DockPanel&gt;
            &lt;ListBox ItemsSource=&quot;{Binding MainMenuItems}&quot; 
                     SelectedItem=&quot;{Binding SelectedMainMenuItem}&quot;                         
                     Name=&quot;MainMenu&quot;
                     SelectedIndex=&quot;2&quot;&gt;
                &lt;ListBox.ItemContainerStyle&gt;
                    &lt;Style TargetType=&quot;ListBoxItem&quot;&gt;
                        &lt;Setter Property=&quot;HorizontalContentAlignment&quot; 
                    Value=&quot;Stretch&quot;/&gt;
                    &lt;/Style&gt;
                &lt;/ListBox.ItemContainerStyle&gt;
                &lt;ListBox.ItemTemplate&gt;
                    &lt;DataTemplate&gt;
                        &lt;DockPanel&gt;                                
                            &lt;TextBlock Text=&quot;{Binding Name}&quot;/&gt;
                        &lt;/DockPanel&gt;
                    &lt;/DataTemplate&gt;
                &lt;/ListBox.ItemTemplate&gt;
            &lt;/ListBox&gt;
        &lt;/DockPanel&gt;
    &lt;/GroupBox&gt;
    &lt;GroupBox Header=&quot;Панель&quot; Grid.Column=&quot;1&quot;&gt;
        &lt;Grid&gt;
            &lt;Grid.RowDefinitions&gt;
                &lt;RowDefinition Height=&quot;50&quot;/&gt;
                &lt;RowDefinition/&gt;
            &lt;/Grid.RowDefinitions&gt;
            &lt;StackPanel Grid.Row=&quot;0&quot;&gt;
                &lt;TextBlock Text=&quot;{Binding TitleDetail}&quot; FontSize=&quot;26&quot;/&gt;
                &lt;Separator Background=&quot;DarkBlue&quot;/&gt;
            &lt;/StackPanel&gt;
            &lt;ContentControl Grid.Row=&quot;1&quot; Content=&quot;{Binding CurrentView}&quot; /&gt;
        &lt;/Grid&gt;
    &lt;/GroupBox&gt;

    &lt;GridSplitter Grid.Column=&quot;0&quot; HorizontalAlignment=&quot;Right&quot; Width=&quot;3&quot;/&gt;
&lt;/Grid&gt;

</Window>

eusataf
  • 249
  • 1
  • 8
  • Совет на будущее: Делайте минимальный, самодостаточный пример, на голом WPF проекте, который опишет конкретную проблему, которую вы хотите решить на простых примитивах. Разбираться в огромной портянке чужого кода мало кто хочет разбираться (думаю вы тоже), поэтому вставайте на место тех, кто не знаком с вами, не знаком с вашими навыками, проектом. и так далее. Представьте, что мы прохожие на улице, вам надо за 5 минут максимально объяснить суть, сможете - помогут, нет - извините... Что касается проблемы - смотрите этот ответ: https://ru.stackoverflow.com/a/816149/220553 – EvgeniyZ Nov 14 '23 at 20:03
  • @EvgeniyZ Понимаю... Прошу извинить... Но не знаю как сделать куском... Частями всё работает... Собираю в проект: не работает... Так, что вот так... Приношу извинения... – eusataf Nov 14 '23 at 20:09

1 Answers1

1

Забыто указание модификатора доступа для свойства в файле /ViewModels/Views/ManagerIndexesViewModel.cs.
Из-за этого свойство оказывается приватным и недоступным для WPF, его как будто нет :)

Ваш код:

public class ManagerIndexesViewModel : BaseVM
{
    IndexesViewModel IndexesViewModel2 { get; }

Надо так:

public class ManagerIndexesViewModel : BaseVM
{
    public IndexesViewModel IndexesViewModel2 { get; }
velial
  • 1,646