WPF Listview + GridView - Просмотр не обновляется - PullRequest
0 голосов
/ 06 августа 2009

У меня есть элемент Listview с дочерним элементом Gridview, связанный со списком объектов. Ниже Gridview у меня есть texbox для редактирования содержимого Gridview (привязанного к Gridview). Я могу добавить новый контент (который отображается в GridView). Когда я редактирую контент, он фактически редактируется (в списке объектов), но не отображается в Gridview (GridView, похоже, не обновляется)

код xaml:

<!-- ========= -->
<!-- root Grid -->
<!-- ========= -->
<Grid x:Name="root" Margin="10,10,10,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="25" />
        <RowDefinition Height="25" />
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <!-- ========= -->
    <!-- Data Grid -->
    <!-- ========= -->
    <ListView x:Name="dataGrid" Grid.Row="0" Grid.ColumnSpan="2" ItemsSource="{Binding}">
        <ListView.View>
            <GridView>
                <!-- first solution -->
                <GridViewColumn x:Name="gridColumnName" Header="Name" Width="160">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ContentControl Content="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <!-- second solution -->
                <GridViewColumn x:Name="gridColumnPath" Header="Path" DisplayMemberBinding="{Binding Path=Path}" Width="490" />
            </GridView>
        </ListView.View>
    </ListView>

    <!-- ========= -->
    <!-- Edit Menu -->
    <!-- ========= -->
    <Label Content="Name:" Grid.Row="1" Grid.Column="0" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
    <TextBox x:Name="txtBoxName" Grid.Row="1" Grid.Column="1" Width="250" VerticalAlignment="Bottom" HorizontalAlignment="Left" 
             DataContext="{Binding ElementName=dataGrid, Path=SelectedItem}" 
             Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

    <Label Content="Path:" Grid.Row="2" Grid.Column="0" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
    <TextBox x:Name="txtBoxPath" Grid.Row="2" Grid.Column="1" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" 
             DataContext="{Binding ElementName=dataGrid, Path=SelectedItem}" 
             Text="{Binding Path=Path, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Класс объектов списка:

class ItemList : ObservableCollection<LdapItem>
{
    public ItemList()
        : base()
    { 
    }
}

Класс объекта:

class LdapItem : INotifyPropertyChanged
{
    #region constructor

    public LdapItem(String name, String path)
    {
        this.iD = Guid.NewGuid().ToString();
        this.name = name;
        this.path = path;
    }

    #endregion

    #region public proterties

    public String ID
    {
        get { return iD; }
    }

    public String Name
    {
        get { return name; }
        set { name = value; }
    }

    public String Path
    {
        get { return path; }
        set { path = value; }
    }

    #endregion

    #region public methods

    public void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }

    #endregion

    #region private variables

    private String name = String.Empty;
    private String path = String.Empty;
    private String iD = String.Empty;

    #endregion

    public event PropertyChangedEventHandler PropertyChanged;
}

есть идеи, почему обновление GridView не работает?

Ответы [ 2 ]

4 голосов
/ 02 августа 2016

Если у вас есть несколько моделей, используйте базовый класс, который реализует INPC. Затем измените свойство, изменившее обработчик событий на:

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Это избавит от необходимости указывать изменяемое свойство модели. Уменьшает количество ошибок, связанных с орфографическими ошибками, или забывает вводить имя. По-прежнему необходимо вызывать this.OnPropertyChanged (), хотя вы его упускаете из нескольких сеттеров.

Класс ItemList не имеет смысла. Может быть заменено на:

public ObservableCollection<LdapItem> LdapItems 
3 голосов
/ 06 августа 2009

похоже, что вы забыли запустить OnPropertyChangedEvent при изменении свойства:

public String Name
{
    get { return name; }
    set { 
           name = value; 
           OnPropertyChanged("Name");
        }
}

Если вы не запустите событие PropertyChanged, WPF не сможет увидеть, изменился ли объект.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...