2016-01-02 51 views
0

我正在使用C#编写WPF应用程序。 该应用程序有3个不同的用户控件(Foo1,Foo2和Foo3),每个至少有一个文本框。 在主窗口上,有一个ListBox将这些UserControls作为它的项目;全部以不同的数量和顺序排列。如何更新XAML列表框中不同类型的项目?

如果我更改这些项目的任何TextBoxes上的Text属性,则更改在ListBox.Items集合发生更改(即添加或删除项目)之前不可见。

如何获取ListBox更新?我试过给用户控件的依赖项属性(标志FrameworkPropertyMetadataOptions.AffectsRender)更新文本框的文本,但没有做任何事情。实现INotifyPropertyChanged并调用PropertyChanged事件也没有效果。

回答

1

我能够改变文本,这个改变的文本出现在ListBox没有问题。

用户控件:

public partial class UserControl1 : UserControl 
    { 
     public UserControl1() 
     { 
      InitializeComponent(); 
      this.DataContext = this; 
     } 

     public string Text 
     { 
      get { return (string)GetValue(TextProperty); } 
      set { SetValue(TextProperty, value); } 
     } 

     // Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty TextProperty = 
      DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata("unset")); 

    } 

窗口1:

public partial class Window1 : Window 
{ 
    IList<UserControl1> ucList = new[] { new UserControl1() { Text = "some text" }, new UserControl1() { Text = "some more value" } }; 

    public Window1() 
    { 
     InitializeComponent(); 

     LstBox.ItemsSource = ucList; 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     ucList[0].Text = DateTime.Now.ToString(); 
     /* Now textbox shows current date-time */ 
    } 
} 

UserControl updation in ListBox

+0

谢谢!这个答案真的帮了我很多!我是一名经验丰富的C#开发人员,但WPF对我而言仍然是新手。这个ItemSource属性看起来非常有用,我肯定会在我的应用程序中实现它。我发现使用UIElements的ObservableCollection还会在添加或删除某些东西时自动更新列表。 – Mark

+0

添加/删除不同于更新项目本身。 – AnjumSKhan

+0

确实如此,但IList的长度是固定的,并且使用不可观察的集合会导致列表在更改集合时不自动更新。但是,由于你的回答,我已经完成了所有工作。 – Mark