0

Хочу сделать, чтобы в окне поверх существующий элементов отображались самые обычные линии (Line), делаю всё это по паттерну MVVM, View (из кода был вырезан стиль для кнопки, т.к проблема вовсе не в нем, а так он бы визуально нагружал):

 <Window.Resources>
    <local:GraphicalKeyViewModel x:Key="GKVM"/>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button Grid.Row="1" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="1" Grid.Column="1" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="1" Grid.Column="2" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="2" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="2" Grid.Column="1" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="2" Grid.Column="2" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="3" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="3" Grid.Column="1" Style="{DynamicResource RoundButton}"/>
    <Button Grid.Row="3" Grid.Column="2" Style="{DynamicResource RoundButton}"/>
    <Image HorizontalAlignment="Right" Height="30" Width="30" Grid.Column="2" Margin="5,5" Source="Resources/Images/CloseButtonPicture.png"/>


    <ItemsControl ItemsSource="{Binding Lines, Source={StaticResource GKVM}, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid IsHitTestVisible="False">
                    <Line X1="{Binding X1}" X2="{Binding X2}" Y1="{Binding Y1}" Y2="{Binding Y2}" StrokeThickness="{Binding StrokeThickness}"
                          Fill="Aqua" Stroke="Aqua"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

ViewModel:

 class GraphicalKeyViewModel : BaseViewModel
{
    ObservableCollection<Line> lines = new ObservableCollection<Line>();
    public ObservableCollection<Line> Lines
    {
        get { return lines;  }
        set
        {
            lines = value;
            OnPropertyChanged();
        }
    }

    public GraphicalKeyViewModel()
    {
        Lines = new ObservableCollection<Line>();
        Line line = new Line()
        {
            X1 = 10,
            Y1 = 10,
            X2 = 100,
            Y2 = 30,
            StrokeThickness = 5,
        };            
        Lines.Add(line);
    }
}

BaseViewModel:

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Суть проблемы в том, что я пытаюсь программно добавить новую линию в коллекцию и она добавляется, но вот почему-то не отображается в окне, в чем может быть проблема??

4
  • Вы не поняли сути MVVM. Во вьюмодели работать напрямую с визуальными элементами нельзя. Иначе весь смысл этого паттерна коту под хвост. С контролами работайте в кодбихайнд.
    – Bulson
    6 дек 2017 в 6:40
  • А где же тогда работать с вью, если не в ней же??? 6 дек 2017 в 7:26
  • Да, во View надо работать с Line, а не как у вас в GraphicalKeyViewModel - это же VM, как я понимаю?
    – Bulson
    6 дек 2017 в 7:32
  • Ааааааа, это я так для примера, я понимаю, что нельзя создавать элементы в VM, просто у меня код не работал, я долго не могу понять в чем проблема и поэтому решил сделать так топорно. 6 дек 2017 в 7:38

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.