【问题标题】:How to bind data user control inside listbox WP8如何在列表框WP8中绑定数据用户控件
【发布时间】:2013-06-08 10:30:31
【问题描述】:

我有一个用户控件。它有一个TextBlock。我想在里面绑定Text

<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;
    }
}

如何正确绑定到用户控件?谢谢!!!

【问题讨论】:

    标签: c# user-controls windows-phone-8


    【解决方案1】:

    从您的UserControl Xaml 中删除此行

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

    控件的 xaml 中的绑定将正确绑定到定义的依赖项属性。你不需要做任何额外的事情。

    如果您与用户控件中的其他数据源存在名称冲突,您可以将ElementName=UserControl 添加到您的绑定中。

    【讨论】:

    • 谢谢我找到了正确绑定数据的方法只有ElementName=nameofUserControl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2012-11-21
    • 1970-01-01
    • 2014-07-16
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多