如何更新XAML ListBox中不同类型的项目?

时间:2016-01-02 06:33:51

标签: c# asp.net wpf xaml listbox

我在C#中使用WPF应用程序。 该应用程序有3个不同的UserControls(Foo1,Foo2和Foo3),每个都有至少一个TextBox。 在主窗口中,有一个ListBox,其中包含这些UserControls作为其项目;所有这些都有不同的数量,没有特别的顺序。

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

如何让ListBox更新?我尝试过提供UserControls依赖项属性(使用标志FrameworkPropertyMetadataOptions.AffectsRender)来更新文本框的文本,但是没有做任何事情。实现INotifyPropertyChanged并调用PropertyChanged事件也没有效果。

1 个答案:

答案 0 :(得分:1)

我可以更改文本,此更改后的文本会显示在ListBox中而不会出现问题。

UserControl:

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"));

    }

Window1:

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