简体   繁体   中英

How to bind data user control inside listbox WP8

I have a user control. It has a 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

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

<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

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

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Binding in the control's xaml will correctly bind to the defined dependency properties. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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