您好,我在强制更新列表视图时遇到了一点问题。我有 ObservableCollection,它包含具有属性 Buffer 的 TestClass 对象。
ObservalbeCollection 驻留在 ViewModel BaseViewModel
public partial class MainPage : PhoneApplicationPage {
// Constructor
public MainPage() {
InitializeComponent();
this.DataContext = new BaseViewModel();
}
}
}
public class BaseViewModel : INotifyPropertyChanged {
public ObservableCollection<TestClass> TestList { get; set; }
public BaseViewModel() {
TestList = new ObservableCollection<TestClass>();
TestList.Add(new TestClass() { Buffer = "1", SomeValue = 1 });
TestList.Add(new TestClass() { Buffer = "2", SomeValue = 2 });
TestList.Add(new TestClass() { Buffer = "3", SomeValue = 3 });
TestList.Add(new TestClass() { Buffer = "4", SomeValue = 4 });
}
private TestClass selectedItem;
public TestClass SelectedItem {
get {
return selectedItem;
}
set {
if (selectedItem == value) {
return;
}
selectedItem = value;
selectedItem.Buffer += "a";
selectedItem.SomeValue += 1;
selectedItem = null;
RaisePropertyChanged("SelectedItem");
}
}
#region notifie property changed
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
public class TestClass : INotifyPropertyChanged {
public TestClass() {
}
public int SomeValue { get; set; }
private string buffer;
public string Buffer {
get {
return this.buffer;
}
set {
this.buffer = value;
RaisePropertyChanged("Buffer");
}
}
#region notifie property changed
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
我正在将视图模型绑定到 Page。
页面xml:
<phone:PhoneApplicationPage
xmlns:converters="clr-namespace:PhoneApp2.Test">
<phone:PhoneApplicationPage.Resources>
<converters:TestClassConverter x:Key="testConverter"/>
</phone:PhoneApplicationPage.Resources>
<ListBox Grid.Row="1" x:Name="tasksListBox" ItemsSource="{Binding TestList}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="SomeText"/>
<TextBlock Text="{Binding Path=Buffer}"/>
<TextBlock Text="{Binding Converter={StaticResource testConverter}}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在第二个文本块在缓冲区更改时正确更新,但第三个仅更新一次(在列表加载时)。转换器只被调用一次。
我想使用第三个选项,因为:
a) 我使用 TestCalass 作为其他子类的基类
b)我想根据 TestClass 类型格式化输出并使用在 TestClass 中设置的其他参数
c) 我想使用 Localizable String 资源,但我不想在 TestClass 中使用它们,而是使用 POCO 对象。
编辑:我已经更新了源代码。第二个文本框发生变化,而第三个没有。所有类都期望 MainPage 驻留:
namespace PhoneApp2.Test