WPF MVVM Кнопка внутри строки просмотра списка не работает, если сначала не щелкнуть строку - PullRequest
0 голосов
/ 27 июня 2018

enter image description here

У меня есть две кнопки внутри списка в каждой строке. один для отображения выбранного элемента, а другой для отображения номера индекса. кнопка для отображения выбранного элемента работает нормально, но кнопка для отображения номера индекса не работает.

Когда я нажимаю кнопку (показывает номер индекса) , возвращается нулевой номер индекса «0», я имею в виду, что он не работает должным образом. но когда я выбираю строку и затем нажимаю кнопку, то она работает, я имею в виду, что она возвращает правильный порядковый номер. то, что я хочу, это кнопка (с указанием номера индекса) должна работать без выбора строки.

ниже код xaml

<ListView                       
    Grid.Row="1"
    ItemContainerStyle="{StaticResource FileItemStyle}"
    ItemsSource="{Binding CollViewSourceBarCode.View, IsAsync=True}"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    SelectedIndex="{Binding SelectedIndex}"
    SelectedItem="{Binding SelectBarCode, UpdateSourceTrigger=PropertyChanged}"
    SelectionMode="Extended"
    Style="{StaticResource ListItemsMain}"
..

ниже приведен код кнопки для выбранного элемента, который отлично работает

<Button
   Command="{Binding DataContext.SelectedItemCommand, RelativeSource={RelativeSource AncestorType=ListView}}"
   Content="{Binding SelectedItemContent}" />

с #

private ICommand mSelectedItemCommand;
public ICommand SelectedItemCommand
    {
        get
        {
            if (mSelectedItemCommand== null)
            {
                mSelectedItemCommand= new DelegateCommand(delegate ()
                {
                    MessageBox.Show(SelectBarCode.BarCodeEntry_ID.ToString());

                });
            }
            return mSelectedItemCommand;
        }
    }

и ниже код для выбора номера индекса, который не работает

<Button
   Command="{Binding DataContext.SelectedIndexCommand, RelativeSource={RelativeSource AncestorType=ListView}}"
   Content="{Binding SelectedIndexContent}" />

с #

private ICommand mSelectedIndexCommand;
public ICommand SelectedIndexCommand
    {
        get
        {
            if (mSelectedIndexCommand== null)
            {
                mSelectedIndexCommand= new DelegateCommand(delegate ()
                {
                    MessageBox.Show(SelectedIndex.ToString());

                });
            }
            return mSelectedIndexCommand;
        }
    }

Обновление ниже приведен полный стиль для ListViewItem

<Style x:Key="FileItemStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="Margin" Value="5,5,5,5" />
        <Setter Property="Padding" Value="0,0,0,0" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="Background" Value="Green" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                    <Grid
                        Width="195"
                        Height="auto"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Top">
                        <Border>
                            <Border.Background>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                                    <GradientStop x:Name="GradientStop1" Offset="0.0" Color="#FF2C302C" />
                                    <GradientStop x:Name="GradientStop2" Offset="0.25" Color="#FF3E3C3C" />
                                    <GradientStop x:Name="GradientStop3" Offset="0.75" Color="#FF3E3C3C" />
                                    <GradientStop x:Name="GradientStop4" Offset="1.0" Color="#FF3E3D3C" />
                                </LinearGradientBrush>
                            </Border.Background>

                            <Border.Triggers>
                                <EventTrigger RoutedEvent="Border.MouseEnter">
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation
                                                Storyboard.TargetName="GradientStop1"
                                                Storyboard.TargetProperty="Offset"
                                                From="0.0"
                                                To="1.0"
                                                Duration="0:0:0.25" />
                                            <ColorAnimation
                                                Storyboard.TargetName="GradientStop4"
                                                Storyboard.TargetProperty="Color"
                                                To="DarkGray"
                                                Duration="0:0:0.25" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </EventTrigger>
                                <EventTrigger RoutedEvent="Border.MouseLeave">
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <DoubleAnimation
                                                Storyboard.TargetName="GradientStop1"
                                                Storyboard.TargetProperty="Offset"
                                                From="1.0"
                                                To="0.0"
                                                Duration="0:0:0.25" />
                                            <ColorAnimation
                                                Storyboard.TargetName="GradientStop4"
                                                Storyboard.TargetProperty="Color"
                                                To="#FF3E3C3C"
                                                Duration="0:0:0.25" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </EventTrigger>



                            </Border.Triggers>
                            <Border.Style>
                                <Style TargetType="Border">
                                    <!--<Setter Property="Background" Value="#FF3E3C3C" />-->
                                    <Setter Property="HorizontalAlignment" Value="Stretch" />
                                    <Setter Property="VerticalAlignment" Value="Stretch" />
                                    <Setter Property="BorderBrush" Value="{x:Null}" />
                                    <Setter Property="BorderThickness" Value="1" />
                                    <Setter Property="CornerRadius" Value="15" />
                                    <Style.Triggers>
                                        <Trigger Property="IsMouseOver" Value="True">
                                            <Setter Property="Cursor" Value="Hand" />

                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </Border.Style>
                        </Border>
                        <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <ContentPresenter />
                        </StackPanel>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="IsSelected" Value="True" />
            </Trigger>
        </Style.Triggers>

    </Style>

Обновление 2: ObserverableCollection

public ObservableCollection<BarCodeModel> BarCode
    {
        get
        {
            mBarCode = mBarCode ?? new ObservableCollection<BarCodeModel>();
            return mBarCode;
        }
    }

тонкий в конструкторе, я назначаю его CollViewSourceBarCode

CollViewSourceBarCode = new CollectionViewSource();
CollViewSourceBarCode.Source = BarCode;

Код для выбранного элемента

public BarCodeModel mSelecBarCode;
    public BarCodeModel SelectBarCode
    {
        get => mSelecBarCode;
        set
        {
            if (value != null)
            {
                mSelecBarCode = value;                    
                OnPropertyChanged("SelectBarCode");
            }
        }
    }

код для выбранного индекса

private int mSelectedIndex;
    public int SelectedIndex
    {
        get => mSelectedIndex;
        set
        {
            mSelectedIndex = value;
            OnPropertyChanged("SelectedIndex");
        }
    }

1 Ответ

0 голосов
/ 27 июня 2018

Так что проблема была SelectionMode. Это должно быть Single.

<ListView                       
    Grid.Row="1"
    ItemContainerStyle="{StaticResource FileItemStyle}"
    ItemsSource="{Binding CollViewSourceBarCode.View, IsAsync=True}"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    SelectedIndex="{Binding SelectedIndex}"
    SelectedItem="{Binding SelectBarCode, UpdateSourceTrigger=PropertyChanged}"
    SelectionMode="Single"
    Style="{StaticResource ListItemsMain}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...