Как правильно реализовать привязку между элементами и массивами?

Есть шаблон данных:
<DataTemplate x:Key="ControlChannelDevice">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
            <RowDefinition Height="34"/>
        </Grid.RowDefinitions>

        <Label Grid.Column="0" Grid.Row="0" Content="Text_1" HorizontalAlignment="Center"/>
        <Label Grid.Column="1" Grid.Row="0" Content="Text_2" HorizontalAlignment="Center"/>

        <Button Grid.Column="0" Grid.Row="1" Content="Command_1" Command="{Binding Command_1}"/>
        <Button Grid.Column="1" Grid.Row="1" Content="Command_2" Command="{Binding Command_2}"/>

        <ToggleButton Grid.Column="0" Grid.Row="2" Content="Status_1" IsChecked="{Binding Status_1}"/>
        <ToggleButton Grid.Column="1" Grid.Row="2" Content="Status_2" IsChecked="{Binding Status_2}"/>

        <ToggleButton Grid.Column="0" Grid.Row="3" Content="Status_3" IsChecked="{Binding Status_3}"/>
        <ToggleButton Grid.Column="1" Grid.Row="3" Content="Status_4" IsChecked="{Binding Status_4}"/>

        <Label Grid.Column="0" Grid.Row="4" Content="Select_1"/>
        <ComboBox Grid.Column="1" Grid.Row="4" SelectedIndex="{Binding Select_1}"/>

        <Label Grid.Column="0" Grid.Row="5" Content="Select_2"/>
        <ComboBox Grid.Column="1" Grid.Row="5" SelectedIndex="{Binding Select_2}"/>

        <Label Grid.Column="0" Grid.Row="6" Content="Select_3"/>
        <ComboBox Grid.Column="1" Grid.Row="6" SelectedIndex="{Binding Select_3}"/>

        <Label Grid.Column="0" Grid.Row="7" Content="Select_4"/>
        <ComboBox Grid.Column="1" Grid.Row="7" SelectedIndex="{Binding Select_4}"/>

    </Grid>
</DataTemplate>

И есть класс с ViewModel - ControlDevice.
Написал код для обработки событий.
public class ControlChannelsDevice : BaseViewModel
{
    public ControlChannelsDevice()
    {
        foreach (ControlDevice elements in ControlChannelDevice)
            elements.PropertyChanged += Elements_PropertyChanged;
    }

    private void Elements_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        RaisePropertyChanged();
    }

    ControlDevice[] _controlChannelDevice = new ControlDevice[4]
    {
        new ControlDevice(),
        new ControlDevice(),
        new ControlDevice(),
        new ControlDevice()
    };
    public ControlDevice[] ControlChannelDevice => _controlChannelDevice;
    
}


Создаю элементы:
<ContentControl Grid.Row="1" Name="Channel_1" ContentTemplate="{StaticResource ControlChannelDevice}"/>
<ContentControl Grid.Row="1" Name="Channel_2" ContentTemplate="{StaticResource ControlChannelDevice}"/>
<ContentControl Grid.Row="1" Name="Channel_3" ContentTemplate="{StaticResource ControlChannelDevice}"/>
<ContentControl Grid.Row="1" Name="Channel_4" ContentTemplate="{StaticResource ControlChannelDevice}"/>

И делаю привязки:
ControlChannelsDevice ControlChannelsDevice { get; set; } = new ControlChannelsDevice ();

Channel_1.DataContext = ControlChannelsDevice.ControlChannelDevice[0];
Channel_2.DataContext = ControlChannelsDevice.ControlChannelDevice[1];
Channel_3.DataContext = ControlChannelsDevice.ControlChannelDevice[2];
Channel_4.DataContext = ControlChannelsDevice.ControlChannelDevice[3];

И подписал на это всё событие. Но почему-то не работают события.
Если просто один элемент создать без массива и привязать, то работает нормально. Изначально в шаблоне данных вместо ключа стоял DataType для ControlDevice.
Пробовал вместо шаблона данных поставить UserControl, а вместо ContentTemplate - Content. События есть, но данные почему-то одни и те же на все четыре ContentControl. При переключении на следующий ContentControl, предыдущий больше не восстанавливается (исчезает).
С массивами в другом участке программы это работает прекрасно, но они работают напрямую со свойствами. А такой подход на текущем не сработал.

Как решить проблему со связкой?
  • Вопрос задан
  • 82 просмотра
Решения вопроса 1
@AquariusStar Автор вопроса
Проблема решилась.
Надо было исправить:
<ContentControl Grid.Row="1" Name="Channel_1" Content="{Binding ControlChannelDevice[0]}"/>
<ContentControl Grid.Row="1" Name="Channel_2" Content="{Binding ControlChannelDevice[1]}"/>
<ContentControl Grid.Row="1" Name="Channel_3" Content="{Binding ControlChannelDevice[2]}"/>
<ContentControl Grid.Row="1" Name="Channel_4" Content="{Binding ControlChannelDevice[3]}"/>

и:
Channel_1.DataContext = ControlChannelsDevice;
Channel_2.DataContext = ControlChannelsDevice;
Channel_3.DataContext = ControlChannelsDevice;
Channel_4.DataContext = ControlChannelsDevice;
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы