[英]How to bind data user control inside listbox WP8
我有一個用戶控件。 它具有一個TextBlock
。 我想在其中綁定文本
<UserControl x:Class="PhoneApp1.MyUserControl"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel Width="200" Height="200" Background="Red">
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
在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
它無法正常工作
<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>
和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;
}
}
如何正確綁定用戶控件? 謝謝!!!
從您的UserControl
Xaml中刪除此行
DataContext="{Binding RelativeSource={RelativeSource Self}}"
控件的xaml中的綁定將正確綁定到已定義的依賴項屬性。 您無需執行任何其他操作。
如果您的用戶控件中的名稱與其他數據源沖突,則可以將ElementName=UserControl
添加到綁定中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.