简体   繁体   English

如何在XAML列表框中更新不同类型的项目?

[英]How do I update items of different types in a XAML ListBox?

I'm working on a WPF application in C#. 我正在使用C#开发WPF应用程序。 The application has 3 different UserControls (Foo1, Foo2 and Foo3), each one has at least one TextBox. 该应用程序具有3个不同的UserControl(Foo1,Foo2和Foo3),每个都有至少一个TextBox。 On the main window, there's a ListBox that has these UserControls as its items; 在主窗口中,有一个列表框,其中将这些UserControls作为其项。 all in different quantities and in no particular order. 全部以不同的数量排列,没有特定的顺序。

If I change the Text property on any of these item's TextBoxes, the change is not visible until the ListBox.Items collection is changed (ie an item is added or removed). 如果我更改了这些项目的任何TextBoxes上的Text属性,则在ListBox.Items集合更改(即添加或删除项目)之前,更改是不可见的。

How do I get the ListBox to update? 我该如何更新ListBox? I've tried giving the UserControls dependency properties (with the flag FrameworkPropertyMetadataOptions.AffectsRender) that updates the textbox's text, but that didn't do anything. 我尝试提供UserControls依赖项属性(带有FrameworkPropertyMetadataOptions.AffectsRender标志),以更新文本框的文本,但没有执行任何操作。 Implementing INotifyPropertyChanged and invoking the PropertyChanged event had no effect either. 实现INotifyPropertyChanged和调用PropertyChanged事件也无效。

I am able to change the Text, this changed Text appears in ListBox without problems. 我可以更改文本,此更改后的文本将出现在ListBox而不会出现问题。

UserControl : 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 : 窗口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 */
    }
}

ListBox中的UserControl更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM