如何在没有
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”标签内容。
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";
int index = YourListview.SelectedIndex; // find the selected index
ListViewItem dummy = new(); //create new listviewitem
YourDataObejct dataObj = new("Apple", "Bannana"); //create your data object wit hthe updated data
dummy.Content = dataObj ; // put that obejct in your new listviewitem
YourListview.Items[index] = dummy; // add the listviewitem to the listview