Gabee8
Gabee8

Reputation: 61

How to change wpf listview item text

How to change wpf listview item text without listview1.Items[0].Refresh(); method?

My xaml code:

<ListView Height="233" HorizontalAlignment="Left" Margin="0,78,0,0" Name="listView1" VerticalAlignment="Top" Width="503" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn x:Name="GridViewColumnName1" Header="Files" Width="120">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Grid Width="{Binding ActualWidth, ElementName=GridViewColumnName1}">
                                <StackPanel Orientation="Vertical" Grid.Column="1" Margin="8,0">
                                    <StackPanel Orientation="Horizontal">

                                        <Label Content="{Binding ItemsName,Mode=TwoWay}" Name="listnameLB"></Label>

                                    </StackPanel>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

My code:

private ListViewItemsData ListviewObject;
public class ListViewItemsData
{
    public string ItemsName { get; set; }
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    listView1.Items.Add(new ListViewItemsData()
    {
        ItemsName = "ABCD"
    });
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    //ListviewObject = new ListViewItemsData();
    ListviewObject = (ListViewItemsData)listView1.Items[0];
    ListviewObject.ItemsName = "EFGH";
    //listView1.Items.Refresh();
}

I want to change "ItemsName" label content for button1 event.

Upvotes: 3

Views: 3151

Answers (2)

Stanislav Vladev
Stanislav Vladev

Reputation: 39

 int index = YourListview.SelectedIndex; // find the selected index

YourDataObejct dataObj = new("Apple", "Bannana"); //new data object

YourListview.Items[index] = dummy; // update item

Upvotes: 1

mm8
mm8

Reputation: 169200

The ListViewItemsData class should implement the INotifyPropertyChanged and raise the PropertyChanged event in the setter of the data-bound ItemsName property:

public class ListViewItemsData : INotifyPropertyChanged
{
    private string _itemsName;
    public string ItemsName
    {
        get { return _itemsName; }
        set { _itemsName = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

(Only) then this should work:

ListviewObject.ItemsName = "EFGH";

Upvotes: 1

Related Questions