2016-01-02 50 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