【问题标题】:Combobox binding breaks when dropped down下拉时组合框绑定中断
【发布时间】:2015-12-17 21:03:28
【问题描述】:

我有一个ComboBox,它绑定到我的表单上的DependencyProperty。我可以通过Button 单击将项目添加到此属性,它会将它们添加到ComboBox。但是,一旦我放下ComboBox,绑定就会中断。我仍然可以向属性添加项目,但我的 ComboBox 永远不会更新以显示它们。

例如

  • 点击Button三次
  • 放下ComboBox - 它将包含三个项目
  • 再点击Button 三次
  • 放下ComboBox - 它仍然只有三个项目

再次启动应用程序并:

  • 点击Button六次
  • 放下ComboBox - 它将有六个项目

XAML

<Grid x:Name="LayoutRoot"
      Background="White">
    <ComboBox Name="combTest"
              ItemsSource="{Binding Users}"
              Width="50"
              Height="50"
              HorizontalAlignment="Left" />
    <Button Click="ButtonBase_OnClick"
            Width="50"
            Height="50"
            HorizontalAlignment="Right" />
</Grid>

代码隐藏

public MainPage()
{
    InitializeComponent();
    this.DataContext = this;
}

public static readonly DependencyProperty UsersProperty = DependencyProperty.Register(
 "Users", typeof (List<string>), typeof (MainPage), new PropertyMetadata(new List<string>()));

public List<string> Users
{
    get { return (List<string>) GetValue(UsersProperty); }
    set { SetValue(UsersProperty, value); }
}

private int i = 0;

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
   Users.Add("User " + i++);
}

【问题讨论】:

    标签: c# silverlight data-binding


    【解决方案1】:

    使用 ObservableCollection 而不是 List

    ObservableCollection 会引起在集合中添加和删除项目的属性更改,但 List 不会。

    【讨论】:

    • 要添加到此答案,将List 作为 DependencyProperty 只会引发对列表本身的更改,而不是其内容。所以如果你做Users = new List&lt;string&gt;(),它会被更新,但如果你只是使用它的一种方法,比如Add
    猜你喜欢
    • 2021-09-08
    • 2018-03-18
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2014-08-13
    相关资源
    最近更新 更多