[英]How to bind data user control inside listbox WP8
I have a user control. 我有一个用户控件。 It has a TextBlock
. 它具有一个TextBlock
。 I want to bind Text in it 我想在其中绑定文本
<UserControl x:Class="PhoneApp1.MyUserControl"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel Width="200" Height="200" Background="Red">
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
In MyUserControls.xaml.cs
在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);
}
}
}
When I bind to ListBox
it doesn't work correctly 当我绑定到ListBox
它无法正常工作
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="mainListBox" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:MyUserControl Text="{Binding Text}" Margin="5"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
and MainPage.xaml 和MainPage.xaml
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<User> list = new ObservableCollection<User>();
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;
}
}
How to bind to user controls correctly? 如何正确绑定用户控件? Thanks!!! 谢谢!!!
Remove this line from your UserControl
Xaml 从您的UserControl
Xaml中删除此行
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Binding in the control's xaml will correctly bind to the defined dependency properties. 控件的xaml中的绑定将正确绑定到已定义的依赖项属性。 You don't need to do anything extra. 您无需执行任何其他操作。
If you have name conflicts with other data sources in your user control you can add ElementName=UserControl
to your binding. 如果您的用户控件中的名称与其他数据源冲突,则可以将ElementName=UserControl
添加到绑定中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.