如何更改wpf listview项目文本

时间:2017-05-31 11:45:19

标签: c# wpf listview

如何在没有listview1.Items[0].Refresh();方法的情况下更改wpf listview项目文本?

我的xaml代码:

<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>

我的代码:

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();
}

我想更改button1事件的“ItemsName”标签内容。

1 个答案:

答案 0 :(得分:0)

ListViewItemsData类应实现INotifyPropertyChanged并在数据绑定PropertyChanged属性的setter中引发ItemsName事件:

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));
    }
}

(仅)然后这应该工作:

ListviewObject.ItemsName = "EFGH";