我是Windows手机开发的新手。我有一个名为' State'的班级。它保留了州的名称和资本。我已经实现了INotifyPropertyChanged接口。
public class State:INotifyPropertyChanged
{
private string _name;
private string _capital;
public State() { }
public State(string name, string capital)
{
this.Name=name;
this.Capital=capital;
}
public string Name
{ get
{
return _name;
}
set
{
_name=value;
OnPropertyChanged(this,"Name");
OnPropertyChanged(this, "Name");
}
}
public string Capital
{
get
{
return _capital;
}
set
{
_capital = value;
OnPropertyChanged(this, "Capital");
OnPropertyChanged(this, "Name");
}
}
public override string ToString()
{
return (Name + " " + Capital );
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(object sender,string Property)
{
if (PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(Property));
}
}
}
ObservableCollection维护我的状态列表。我想更新Collection中一个元素的一个属性的更改,并反映ListBox中的更改。但是没有反映出这些变化。这是我的MainPage类。我在按钮点击事件上更改了属性值。
public partial class MainPage : PhoneApplicationPage
{
private ObservableCollection<State> MyStatelist;
public MainPage()
{
InitializeComponent();
MyStatelist = new ObservableCollection<State>();
MyStatelist.Add(new State("State1","Capital1"));
States.ItemsSource = MyStatelist;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyStatelist[0].Name = "Abcd";
t1.Text = MyStatelist[0].Name;
}
}
这是我的XAML代码
<ListBox x:Name="States" Margin="0,10" ItemsSource="{Binding MyStatelist Mode=TwoWay}" ScrollViewer.VerticalScrollBarVisibility="Visible" Background="White" Foreground="Black" Height="Auto" Width="Auto" >
</ListBox>
无论如何,我可以通知列表框它必须更新。
非常感谢!!
答案 0 :(得分:0)
您绑定ObservableCollection<State>
两次。首先,在MainPage
构造函数中创建新对象。这就足够了。在XAML ItemsSource="{Binding MyStatelist Mode=TwoWay}"
中执行此操作时,会创建ObservableCollection<State>
的新实例。这就是MyStatelist[0].Name = "Abcd"
无效的原因,因为MyStatelist
不再被设置为项目来源。只需删除XAML中的绑定即可。
还有一件事。您必须将ItemTemplate
添加到ListBox
并正确绑定State
类的属性。这是我的榜样:
<ListBox x:Name="States" Margin="0,10"
Grid.Row="1"
ScrollViewer.VerticalScrollBarVisibility="Visible"
Background="White"
Foreground="Black"
Height="Auto"
Width="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="0, 0, 12, 0"/>
<TextBlock Text="{Binding Capital}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 1 :(得分:0)
您尚未绑定到这些属性。请改用:
<ListBox x:Name="States" Margin="0,10" ScrollViewer.VerticalScrollBarVisibility="Visible" Background="White" Foreground="Black" Height="Auto" Width="Auto" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="Name" />
<Binding Path="Capital" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>