如何在列表框WP8中绑定数据用户控件
我有一个用户控件。 它有一个TextBlock
。 我想在其中绑定Text
在MyUserControls.xaml.cs
public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(MyUserControl), new PropertyMetadata(null)); public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } }
当我绑定到ListBox
它无法正常工作
和MainPage.xaml
public partial class MainPage : PhoneApplicationPage { ObservableCollection list = new ObservableCollection(); public MainPage() { InitializeComponent(); User user = new User("Thanh"); list.Add(user); list.Add(new User("lfjlkgj")); DataContext = list; } } public class User { public string Text { get; set; } public User(string name) { Text = name; } }
如何正确绑定到用户控件? 谢谢!!!
从UserControl
Xaml中删除此行
DataContext="{Binding RelativeSource={RelativeSource Self}}"
控件的xaml中的绑定将正确绑定到已定义的依赖项属性。 你不需要做任何额外的事情。
如果您的用户控件中的名称与其他数据源冲突,则可以将ElementName=UserControl
添加到绑定中。