[英]ListView not updating when observed collection changes?
我具有下面的UI,該UI允許您在左側選擇一個團隊,然后在右側編輯所選團隊的屬性。 這是演示此問題的示例方案:
團隊列表存儲為可觀察的集合:
public class TeamList : ObservableCollection<Team>
{
public TeamList() : base() { }
}
左側的團隊列表正在填充/綁定:
SettingsWindow.xaml
<ListView ItemsSource="{Binding}" Grid.Column="0" Grid.Row="1" DisplayMemberPath="name"
SelectionChanged="ListTeamSelected" SelectionMode="Single">
<!--<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Foreground" Value="{Binding color}" />
</Style>
</ListView.ItemContainerStyle>-->
</ListView>
SettingsWindow.xaml.cs
public Team selectedTeam { get; set; }
public SettingsWindow()
{
teams = TeamManager.Instance().teamList;
this.DataContext = this.teams;
if (!Application.Current.Resources.Contains("selectedTeam"))
Application.Current.Resources.Add("selectedTeam", selectedTeam);
InitializeComponent();
}
右側的數據正在填充並保存:
SettingsWindow.xaml.cs
private void ClickSaveData(object sender, RoutedEventArgs e)
{
selectedTeam.name = TeamName.Text;
selectedTeam.color = PrimaryColorPicker.SelectedColor;
selectedTeam.secondaryColor = SecondaryColorPicker.SelectedColor;
saved = true;
}
private void ListTeamSelected(object sender, RoutedEventArgs e)
{
selectedTeam = (Team)(sender as ListView).SelectedItems[0];
TeamInfo.Visibility = Visibility.Visible;
TeamName.Text = selectedTeam.name;
PrimaryColorPicker.SelectedColor = selectedTeam.color;
SecondaryColorPicker.SelectedColor = selectedTeam.secondaryColor;
}
雙重問題:
我的數據綁定有什么問題嗎? (我是WPF的新手)
如果沒有,我是否可以強制UI更新左側的列表? (對我來說這似乎含糊不清)
預先感謝您的協助!
我不知道我的Team
類實現INotifyPropertyChanged。 該鏈接非常有用且直接。 對於以前從未使用過數據綁定的其他人,需要注意以下幾點:
您需要為要通知的所有屬性使用getter和setter來引發事件。
您需要使用私有變量來保存數據本身,否則設置器將觸發自身,從而使您陷入堆棧溢出。
事件的參數是已更改屬性的公共名稱,而不是私有名稱或值。
感謝@ReggaeGuitar的回答!
您的屬性需要實現INotifyPropertyChanged接口,以使數據綁定正常工作。 例如(來自http://wpftutorial.net/INotifyPropertyChanged.html )
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
PropertyChanged("Name");
}
}
private void PropertyChanged(string prop)
{
if( PropertyChanged != null )
{
PropertyChanged(this, new PropertyChangedEventArgs(prop);
}
}
我強烈建議使用MVVM Light Toolkit來進行任何MVVM工作( https://mvvmlight.codeplex.com/ )。 如果使用MVVM Light Toolkit,則可以從ViewModelBase
繼承,然后實現這樣的屬性
private string _orgId;
public string OrgId
{
get { return _orgId; }
set { _orgId = value; RaisePropertyChanged("OrgId"); }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.