这个例子来自一本教科书,我相信它有一些错误。
在此示例中,创建了一个类昵称,其中包含两个属性名称和 Nick ,以及一个ObservableCollection 昵称< / strong>用于收集昵称。在视图中,有两个文本框供用户填写名称和昵称,一个按钮将这两个值添加到昵称和列表框上的显示项目;如果在列表框中选择了某个项目,则两个文本框应相互显示名称和昵称。
但是,这两个值在列表框中总是杰克和乔,我相信问题很可能就出现了:
public Nickname() : this("Jack", "Joe") { }
如何解决此问题?或者,除了停靠面板以外是否还有其他建议可以满足要求?
Window1.xaml:
<DockPanel x:Name="dockPanel">
<TextBlock DockPanel.Dock="Top">
<TextBlock VerticalAlignment="Center">Name: </TextBlock>
<TextBox Text="{Binding Path=Name}" Width="50"/>
<TextBlock VerticalAlignment="Center">Nick: </TextBlock>
<TextBox Text="{Binding Path=Nick}" Width="50"/>
</TextBlock>
<Button DockPanel.Dock="Bottom" x:Name="addButton">Add</Button>
<ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock Text="{Binding Path=Name}" />:
<TextBlock Text="{Binding Path=Nick}" />
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
Window1.xaml.cs:
public Window1()
{
InitializeComponent();
this.addButton.Click += addButton_Click;
// create a nickname collection
this.names = new Nicknames();
// make data available for binding
dockPanel.DataContext = this.names;
}
void addButton_Click(object sender, RoutedEventArgs e)
{
this.names.Add(new Nickname());
}
Nickname.cs:
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
string name;
public string Name {...}
string nick;
public string Nick {...}
public Nickname() : this("Jack", "Joe") { }
public Nickname(string name, string nick)
{
this.Name = name;
this.Nick = nick;
}
Nicknames.cs:
public class Nicknames : ObservableCollection<Nickname> { }