我能够改变文本,这个改变的文本出现在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 */
}
}
谢谢!这个答案真的帮了我很多!我是一名经验丰富的C#开发人员,但WPF对我而言仍然是新手。这个ItemSource属性看起来非常有用,我肯定会在我的应用程序中实现它。我发现使用UIElements的ObservableCollection还会在添加或删除某些东西时自动更新列表。 – Mark
添加/删除不同于更新项目本身。 – AnjumSKhan
确实如此,但IList的长度是固定的,并且使用不可观察的集合会导致列表在更改集合时不自动更新。但是,由于你的回答,我已经完成了所有工作。 – Mark